初识Eureka
- Spring Cloud Eureka是Spring Cloud Netflix套件的一个组件,基于Netflix Eureka做了二次开发
- 为什么需要服务治理?微服务会越来越多,集群规模、服务位置、服务命名都会发生变化,很难通过静态配置来手工维护大量的微服务实例(想想Zookeeper是怎么配置实例的),我们需要解决微服务架构中的服务实例维护问题。
- Eureka包含了服务端组件(注册中心)和客户端组件(生产者、消费者),也是通过心跳来更新服务
本章核心内容
- 搭建注册中心
- 服务注册和发现
- Eureka的基础架构(后续)
- Eureka的服务治理机制(后续)
- Eureka的配置(后续)
搭建注册中心
- 引入依赖spring-cloud-starter-eureka-server
- 在SpringBoot启动类上贴上@EnableEurekaServer,表明这是一个服务注册中心
- 配置application.properties
# 应用名
spring.application.name=eureka-server
# 主机名
eureka.instance.hostname=peer1
# 启动端口
server.port=1111
# 不向注册中心注册自己
eureka.client.register-with-eureka=false
# 不需要检索
eureka.client.fetch-registry=false
# 注册中心地址
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka
# 本地调试时关闭保护机制
eureka.server.enable-self-preservation=false
服务注册
创建一个生产者
- 引入spring-cloud-starter-eureka
- 在SpringBoot启动类上贴上@EnableDiscoveryClient,表明这是一个客户端
- 配置application.properties
# 应用名
spring.application.name=hello-service
# 端口
server.port=8081
# 注册中心地址
eureka.client.serviceUrl.defaultZone=http://peer1:1111/eureka - 创建一个Controller
@Autowired
private DiscoveryClient discoveryClient;
/** 注意,如果是POST方式且形参是对象,那么需要在参数列表内添加@ResponseBody */
@PostMapping("/hello")
public String hello(String message) {
ServiceInstance instance = discoveryClient.getLocalServiceInstance();
logger.info("message:{}, instance:{}", message, instance.toString());
return "Hi";
}
服务注册注册成功后,控制台会输出status 204
以及注册中心显示服务实例
创建一个消费者
- 与服务注册的1,2,3相同,注意修改应用名和端口,区分
- 在启动类里注册一个Bean
@Bean@LoadBalanced
public RestTemplate restTemplate() {return new RestTemplate();}
创建一个Controller
@Autowired
RestTemplate restTemplate;
@GetMapping("/demo")
public String hello(String message) {
String result = restTemplate.postForObject(
"http://HELLO-SERVICE/hello?message={1}",
"hello",
String.class,
message);
return result;
}
附:eureka实例