---
title: Cloud Foundry ❤️ Spring Boot
tags: ["Cloud Foundry", "Pivotal Web Services", "Pivotal Cloud Foundry", "Spring Boot", "Java"]
categories: ["Programming", "Java", "org", "springframework", "boot"]
date: 2017-01-01T12:26:06Z
updated: 2017-01-12T03:07:50Z
---

Cloud FoundryとSpringはともにPivotalがメインで開発しているが、最近は"Cloud Foundry ❤️ Spring"と
言って、"**Cloud FoundryがSpring Bootの最適な実行環境**"になるように機能追加やシームレスな連携が進んでいる。Spring Boot 1.5では[Spring Boot ActuatorとCloud Foundryの連携](http://docs.pivotal.io/pivotalcf/1-9/console/using-actuators.html)が利用可能になる。

この機能を使うには

* Spring Boot 1.5以上
* [CC API v 2.64.0](https://apidocs.cloudfoundry.org/246/)以上 = [cf-release v246](https://github.com/cloudfoundry/cf-release/releases/tag/v246)以上

が必要。Pivotal版Cloud Foundryの対応状況は次の通り。

* [Pivotal Web Services](https://run.pivotal.io) (パプリックCloud Foundry)
* [Pivotal Cloud Foundry 1.9.0](http://docs.pivotal.io/pivotalcf/1-9)以上 (商用パッケージ版Cloud Foundry)
* [PCF Dev v0.23.0](https://network.pivotal.io/products/pcfdev#/releases/3553)以上 (ローカルCloud Foundry)

Pivotal版Cloud Foundryは管理画面がSpring Bootと連携できるので、基本的にはこの記事で説明する内容は上記の3環境を想定している。

この記事では、現時点で利用可能な機能を紹介する。

> 【注意】 記事執筆時点でSpring Boot 1.5はリリースされておらず、記事の内容は変わる可能性あり。

まずはプロジェクト作成。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/fdadd85e-a74d-a48e-0e92-1b846668d69f.png)

 [Spring Initializr](https://start.spring.io)で今回は次の項目を入力して"Generate Project"ボタンをクリック。hello-cf.zipを展開。

| Artifact      | Search for dependencies | version |
| ------------- |-------------|-------------|
| hello-cf   | Web, Actuator | 1.5.0 |


コマンドラインで雛形プロジェクトを一発で作る場合は、次の通り。

```
$ curl -s https://start.spring.io/starter.tgz \
       -d bootVersion=1.5.0.BUILD-SNAPSHOT \
       -d artifactId=hello-cf \
       -d baseDir=hello-cf \
       -d dependencies=web,actuator \
       -d applicationName=HelloCfApplication | tar -xzvf -

x hello-cf/mvnw
x hello-cf/
x hello-cf/.mvn/
x hello-cf/.mvn/wrapper/
x hello-cf/src/
x hello-cf/src/main/
x hello-cf/src/main/java/
x hello-cf/src/main/java/com/
x hello-cf/src/main/java/com/example/
x hello-cf/src/main/resources/
x hello-cf/src/main/resources/static/
x hello-cf/src/main/resources/templates/
x hello-cf/src/test/
x hello-cf/src/test/java/
x hello-cf/src/test/java/com/
x hello-cf/src/test/java/com/example/
x hello-cf/.gitignore
x hello-cf/.mvn/wrapper/maven-wrapper.jar
x hello-cf/.mvn/wrapper/maven-wrapper.properties
x hello-cf/mvnw.cmd
x hello-cf/pom.xml
x hello-cf/src/main/java/com/example/HelloCfApplication.java
x hello-cf/src/main/resources/application.properties
x hello-cf/src/test/java/com/example/HelloCfApplicationTests.java

$ cd hello-cf
```

`HelloCfApplication`を実行、あるいは`./mvnw spring-boot:run`を実行して空のアプリケーションを起動。
[http://localhost:8080/env](http://localhost:8080/env)にアクセス。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/5f9aa924-6383-d543-9a86-9835a8f3f685.png)

実はSpring Boot 1.5からは`/info`, `/health`を除くActuatorのエンドポイントは**Spring Securityなしでもデフォルトで認可あり**になる。

> 1.4以前のように認可なしにするには[`management.security.enabled=false`を設定する](https://github.com/spring-projects/spring-boot/commit/a19a28062f4229acdf38ee97a8299f303ca1036d)必要がある。もしくは`ROLE_ACTUATOR`権限を持つユーザーでアクセスする必要がある。 ([gh-6889](https://github.com/spring-projects/spring-boot/issues/6889), [gh-7673](https://github.com/spring-projects/spring-boot/issues/7673))


[http://localhost:8080/health](http://localhost:8080/health)と[http://localhost:8080/info](http://localhost:8080/info)に関してはアクセスできる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/580b1318-85a1-0ca7-70aa-14f42f7bbf9b.png)


`/health`と`/info`も認可対象にしたい場合は、`application.properties`に

``` properties
endpoints.health.sensitive=true
endpoints.info.sensitive=true
```

を設定する。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/edbfd700-958e-a7d9-d858-1943c577667c.png)


この状態でこのアプリケーションをCloud Foundryにデプロイする。

今回は[Pivotal Web Services](https://run.pivotal.io)を利用する。アカウント作成方法は[こちら](https://github.com/Pivotal-Japan/cf-workshop/blob/master/pivotal-web-services.md)。

まずはログイン。

```
cf login -a api.run.pivotal.io
```

ビルド。

```
./mvnw package -Dmaven.test.skip=true
```

Cloud Foundryにデプロイ。

```
cf push hello-cf-boot15 -m 256m -p target/hello-cf-0.0.1-SNAPSHOT.jar
```

> `hello-cf-boot15`の部分は、重複しないように変更する必要あり。

では、いよいよ連携機能を見ていく。

[Apps Manager (アプリケーション管理画面)](https://console.run.pivotal.io/)にログイン。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/6c6b696e-96eb-44e1-9063-560fed2601e6.png)

### ヘルスチェック連携

アプリケーション名の左にSpring Bootのロゴが出ていたら、連携成功である。

まずはヘルスチェック連携。Spring Boot Actuatorの`/health`エンドポイントの内容がApps Managerから見れるようになる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/ea703666-e811-154a-4b8e-e8b0a157b344.png)


![image](https://qiita-image-store.s3.amazonaws.com/0/1852/bbbc0d38-799a-0b55-50d8-f08189f52485.png)

">"をクリックすると詳細が見れる。


![image](https://qiita-image-store.s3.amazonaws.com/0/1852/c6f9714c-0946-50c2-7f5d-3b57b123a7e5.png)

"View JSON"をクリックすると、JSON形式(`/health`の結果そのまま)で見ることもできる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/77630777-3f33-d9af-c876-d4e082bf5ab0.png)

もちろん、`endpoints.health.sensitive=true`を設定していても管理画面からはアクセスできる。
ブラウザで直接`/health`エンドポイントにアクセスしても401エラーが返る。

https://hello-cf-boot15.cfapps.io/health

Spring Bootにこの自動認可処理(Spring Security不要)が組み込まれているのが連携ポイントである。

アプリケーションをスケールアウトしても個々のインスタンスのヘルスチェックが可能。

3インスタンスにスケールアウトしてみる。

```
cf scale hello-cf-boot15 -i 3
```

管理画面には次のように表示される。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/1405b49b-412d-33b7-29d3-f8fe2039f904.png)

アプリケーションにMySQLやRabbitMQと言ったバックエンドサービスをバインドした場合は次のように各サービス([Spring Boot Actuatorがサポート](http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#_auto_configured_healthindicators)している場合)のヘルスチェックも見れる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/a23ac240-ed9e-dea7-ced6-7342c4490bbb.png)

ダウンしたサービスがいると次のように表示される。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/0158c438-ea78-4db1-c8d1-60bf97770202.png)


ヘルスチェックは[自分で追加することも可能](http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#_writing_custom_healthindicators)。

### Git連携

次に`/info`連携。

まずは次のように`git-commit-id-plugin`を使って`/info`の結果に[Git情報を埋め込む](http://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#howto-git-info)。

``` xml
	<build>
		<plugins>
			<!-- ... -->
			<plugin>
				<groupId>pl.project13.maven</groupId>
				<artifactId>git-commit-id-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
```

`/info`にアクセスすると次のような結果が返る。(ただし`endpoints.info.sensitive=true`を設定している場合は401になる)

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/7a9c4ecb-0c54-06e7-2b9b-9013b4fc7c66.png)


このアプリケーションを再度ビルド&`cf push`。

```
./mvnw clean package -DskipTests=true && cf push hello-cf-boot15 -m 256m -p target/hello-cf-0.0.1-SNAPSHOT.jar
```

Apps Managerを見ると、"View App"ボタンの下に小さくGitの情報が埋め込まれる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/9074b054-f5fd-9957-3e3f-8af5ec2700df.png)

とても地味だけど、ありがたい。特にマイクロサービスアーキテクチャでたくさんのアプリケーションがデプロイされている場合は、どのバージョンが動いているのかわからなくなりがちなので、組み込みでこのような情報が見れるのは助かる。

ちなみにデプロイされいるアプリは[making/hello-cf#5935679](https://github.com/making/hello-cf/tree/5935679)。

(前に見た時はGitHubのコミットログに飛べたはずだけど、PWS版では飛べない...)
↑[追記] `management.info.git.mode=full`が必要っぽい
ここは今後もう少し改善されていくと思う。

### ログレベルの動的変更

次に`/loggers`連携。

Spring Boot 1.5からはActuatorに`/loggers`エンドポイントが追加され、ログレベルの変更リクエストを送ることができるようになる。([gh-7396](https://github.com/spring-projects/spring-boot/issues/7396))

このエンドポイントを使って、Apps Managerから起動中のアプリケーションのログレベルを動的に変更することができる。

Logsタブを開いて、"Configure Logging Levels"をクリックすると、

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/9d9dbde1-a9e7-5c93-cc4c-82113380b016.png)

ログレベル変更のダイアログが立ち上がる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/0dfacb8e-dd9e-9f0c-b4de-21d317805f07.png)

ここでは`org.spring.framework.web.client.RestTemplate`のログレベルをINFOからDEBUGに変更する。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/bbec33b9-9f8a-c4c3-3698-ac069bed95ac.png)


Logsタブの▶️ボタンをクリックして、ログをTailした状態で、先ほどのHealth Checkの"Vieww JSON"をクリックすると`RestTemplate`のログが流れていることがわかる。

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/dd7f77bd-7162-2b8d-e166-bc9c2ab43989.png)

ちなみにPivotal Web ServicesのCloud Controller API (`api.run.pivotal.io`)に対して、`https://api.run.pivotal.io/v2/apps/:guid/permissions`のリクエストを送っていることがわかる。[このAPI](https://apidocs.cloudfoundry.org/246/apps/retrieving_permissions_on_a_app.html)がcf-release v246以上必須となる。

### (おまけ) Zipkinヘッダー連携

Cloud FoundryのルーターにZipkinのヘッダー(`X-B-Trace-Id`, `X-B3-Span-Id`, `X-B3-ParentSpanId`)がつくようになった。([cf-release v243](https://github.com/openzipkin/zipkin/issues/1251#issuecomment-253684957)以上)

![image](https://qiita-image-store.s3.amazonaws.com/0/1852/b4913c29-79b1-f8e8-f4f1-180259e4196c.png)

これでSpring Cloud Sleuthを入れた場合のSpring BootアプリケーションログとCloud Foundryのリクエストログが結びつく。
ZipkinによるトレーシングもCloud Foundryの入り口から始まるようになる。

今後は[PCF Metrics](http://docs.run.pivotal.io/metrics/using.html)と連携される予定。


---

今後は全Actuatorの機能が管理画面に搭載されている予定。
Spring BootとCloud Foundryの親和性はどんどん高くなっているので、ぜひ試してみてほしい。

* [Cloud Foundryワークショップ資料](https://github.com/Pivotal-Japan/cf-workshop)
* [Spring Cloud Streamチュートリアル](https://github.com/Pivotal-Japan/spring-cloud-stream-tutorial)
