现来说一些Eureka的概念:
1、服务注册 Register
就是Client向Server注册的时候提供自身元数据,比如IP和Port等信息。
2、服务续约 Renew
Client默认每隔30s发送一次心跳来服务续约,如果90s没有收到Client的心跳包,Server会将Client从注册列表中移除。
3、获取服务注册信息 Fetch Register
Eureka Client会从Eureka Server获取服务注册表信息,并将其缓存在本地。默认每30s更新一次。
4、下线 Cancel
Eureka Client在程序关闭的时候可以向Eureka Server发送下线请求立即移除注册表信息,需要手动调用代码:
5、LoadBalancer缓存
Ribbon在客户端维护了缓存定时刷新,避免每个请求都从Server获取注册信息,所以新注册的Provider可能会出现延迟。
DiscoveryManager.getInstance().shutdownComponent();
搭建Eureka Server
配置文件:
server:port: 9001 eureka:instance:hostname: localhostprefer-ip-address: trueclient:register-with-eureka: falsefetch-registry: falseservice-url:defaultZone: http://localhost:9001/eureka/
启动类加注解@EnableEurekaServer:
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication {public static void main(String[] args) {SpringApplication.run(EurekaServerApplication.class, args);} }
访问:http://localhost:9001/
Eureka服务注册
配置文件:
server:port: 9006 spring:application:name: hi-service eureka:client:service-url:defaultZone: http://localhost:9001/eureka/
启动类加注解@EnableEurekaClient:
@SpringBootApplication @EnableEurekaClient public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);} }
Eureka服务发现
配置文件:
server:port: 9008 spring:application:name: eureka-consumer eureka:client:service-url:defaultZone: http://localhost:9001/eureka/
启动类加注解@EnableEurekaClient:
@SpringBootApplication @EnableEurekaClient public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);} }
Service层访问:
@Service public class RibbonService {@AutowiredRestTemplate restTemplate;public String hi() {return restTemplate.getForObject("http://hi-service/hi", String.class);} }
可以看到,url已经使用application name去代替了ip+port的信息去请求服务。如果Eureka Service provider在配置文件中没有配置serviceId,则默认为配置文件中的服务名,也就是${spring.application.name}。
创建Eureka Server服务集群
多profile格式配置文件application.yml
spring:application:name: discovery-cluster --- spring:profiles: discovery1 server:port: 8761 eureka:instance:hostname: discovery1client:service-url:default-zone: http://discovery2:8762/eureka--- spring:profiles: discovery2 server:port: 8762 eureka:instance:hostname: discovery2client:service-url:default-zone: http://discovery1:8761/eureka
配置文件是通过两个Eureka Server互相注册,这里有三段配置,第一段配置为公共配置,配置了应用名称,第二段为名discovery1
的配置,第三段为discovery2
的配置。在项目启动可以通过 --spring.profiles.active={配置名称}
来启动不同的配置。
java -jar discovery-cluster-0.0.1-SNAPSHOT.jar --spring.profiles.active=discovery1
java -jar discovery-cluster-0.0.1-SNAPSHOT.jar --spring.profiles.active=discovery2
在client端,只需要把 eureka.client.serviceUrl.defaultZone
改成相应的集群地址即可,多个服务用逗号分隔:
eurekaclientserviceUrldefaultZone = http://discovery1:8761/eureka,http://discovery2:8761/eureka