遵循SpringBoot三板斧
服务端
第一步加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
|
第二步加注解
1 2 3 4 5 6 7 8
| @EnableEurekaServer @SpringBootApplication public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
|
第三步写配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| spring: application: name: eureka
eureka: datacenter: cloud environment: test instance: hostname: localhost prefer-ip-address: true leaseRenewalIntervalInSeconds: 5 leaseExpirationDurationInSeconds: 10 instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} client: healthcheck: enabled: true registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ server: enableSelfPreservation: true renewalPercentThreshold: 0.85 waitTimeInMsWhenSyncEmpty: 5 response-cache-update-interval-ms: 3000 responseCacheAutoExpirationInSeconds: 180 evictionIntervalTimerInMs: 3000
|
如果是多实例高可用修改下列配置
1 2 3 4 5
| eureka: client: registerWithEureka: true serviceUrl: defaultZone: http://peer2:1112/eureka/,http://peer3:1112/eureka/
|
客户端
第一步加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
|
第二步加注解
1 2 3 4 5 6 7 8
| @EnableDiscoveryClient @SpringBootApplication public class ClientApplication { public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } }
|
第三步写配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| eureka: instance:
preferIpAddress: true instance-id: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${random.int[1,9]}}-@project.version@ leaseRenewalIntervalInSeconds: 30 leaseExpirationDurationInSeconds: 90
metadata-map: zc-data: Current services are goods services zone: ABD
client: service-url: defaultZone: http://localhost:8761/eureka/ enabled: true registerWithEureka: true fetchRegistry: true registry-fetch-interval-seconds: 30 healthcheck: enabled: true
|
最后可以通过DiscoveryClient
对象,在日志中打印出服务实例的相关内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Slf4j @RestController public class TestController { @Autowired private DiscoveryClient discoveryClient;
@GetMapping("/getDiscoveryClient") public List<ServiceInstance> getDiscoveryClient() { return discoveryClient.getInstances("server-1"); }
@GetMapping("/getServices") public List<String> getServices() { return discoveryClient.getServices(); } }
|