更新於 2024/05/27閱讀時間約 6 分鐘

[Java]Spring Boot變Spring Cloud

  • 部署Consul服務
docker run --name consul -p xxxx:xxxx -v /tmp/consul/conf/:/consul/conf/ -v /tmp/consul/data/:/consul/data/ -d consul


  • 於pom.xml設定Spring Cloud parent
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Greenwich.SR1</version>
<relativePath/>
</parent>


  • 於pom.xml設定Spring Cloud dependency
<!--微服務健康性檢查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Consul-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--Hystrix的服務限流熔斷-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!--Spring Cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>


  • 建立bootstrap.yml
spring:
application:
name: user
profiles:
active: debug
cloud:
consul:
host: 127.0.0.1
port: 8500
discovery:
preferIpAddress: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}:@project.version@
healthCheckPath: /actuator/health
server:
port: 9090

設定應用名稱、通訊資訊與註冊Consul服務的相關資訊。


  • 於pom.xml設定Maven
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>

<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/application*.yml</include>
<include>**/application*.yaml</include>
<include>**/bootstrap.yml</include>
<include>**/bootstrap.yaml</include>
</includes>
</resource>
</resources>
</build>

spring boot會預先載入application.yml,但不會載入bootstrap.yml,做了上述設定後,就會載入bootstrap.yml。


  • 於main上,加入底下代碼
@EnableDiscoveryClient

會引入spring-cloud-starter-consul-discovery,並將為服務註冊到consul。



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.