spring cloud(一) 服务注册与发现 Eureka||Consul

深藏阁楼爱情的钟 2022-03-15 07:08 303阅读 0赞

本系列文章均参考:朝雨忆轻尘,感谢博主!

这里还有他的技术交流群:429854222,欢迎大家支持博主

若有侵权,还请告知,一定删除

Spring Cloud Eureka

server:

pom.xml:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-eureka-server</artifactId>
  4. </dependency>

通过@EnableEurekaServer注解启动一个服务注册中心

  1. @EnableEurekaServer
  2. @SpringBootApplication
  3. public class Application {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Application.class,args);
  6. }
  7. }

application.yml:

  1. server:
  2. port: 8888
  3. eureka:
  4. server:
  5. #开启自我保护
  6. enable-self-preservation: true
  7. instance:
  8. #以IP地址注册
  9. preferIpAddress: true
  10. hostname: ${spring.cloud.client.ipAddress}
  11. instanceId: ${spring.cloud.client.ipAddress}:${server.port}
  12. client:
  13. registerWithEureka: false
  14. fetchRegistry: false
  15. serviceUrl:
  16. defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

client:

pom.xml:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-eureka</artifactId>
  4. </dependency>

应用主类中通过加上@EnableEurekaClient注解,启用服务发现(@EnableDiscoveryClient亦可):

  1. @EnableEurekaClient
  2. //@EnableDiscoveryClient
  3. @SpringBootApplication
  4. public class Application {
  5. public static void main(String[] args) {
  6. SpringApplication.run(Application.class,args);
  7. }
  8. }

application.yml:

  1. eureka:
  2. client:
  3. serviceUrl:
  4. defaultZone: http://localhost:8888/eureka/

地址对应即可。

Spring Cloud Consul

server:

consul服务器安装详见我其他博客:传送门

client:

pom.xml:

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-consul-discovery</artifactId>
  4. </dependency>

应用主类中通过加上@EnableDiscoveryClient注解,启用服务发现:

  1. @EnableDiscoveryClient
  2. @SpringBootApplication
  3. public class Application {
  4. public static void main(String[] args) {
  5. SpringApplication.run(Application.class,args);
  6. }
  7. }

application.yml:

  1. spring:
  2. application:
  3. name: applicationName
  4. cloud:
  5. consul:
  6. host: localhost
  7. port: 8500
  8. discovery:
  9. serviceName: ${spring.application.name} # 注册到consul的服务名称

集群:

Eureka集群就是开启多个Eureka微服务,之间互相注册即可。然后客户端的配置defaultZone指定一个到多个都行:传送门

consul集群也类似,开启多个consul服务(当然与单机开启命令不一样),然后服务之间通过join命令来开启一个集群:传送门

好,告辞~

发表评论

表情:
评论列表 (有 0 条评论,303人围观)

还没有评论,来说两句吧...

相关阅读