写在前面:最好的文档是官网和源码。
作为注册中心,主要是实现服务治理功能的。除了Eureka,还可以使用 Consul,Etcd,Zookeeper 等作为服务器的注册中心。
使用Eureka编写注册中心服务
- 创建一个spring boot 工程
- maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath />
</parent>
<!--Spring Cloud-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!--Eureka包依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 启动类增加 @EnableEurekaServer
就是意味着,这个项目是Eureka注册中心服务
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
- 工程配置文件application.properties
spring.application.name=eureka-server
server.port=8761
# 不需要注册自己
eureka.client.register-with-eureka=false
# 注册中心自己就是提供注册的功能,不需要获取在这里注册的服务信息
eureka.client.fetch-registry=false
- 直接在浏览器访问 http://localhost:8761 就可以看到Spring cloud自带的服务管理页面了。
编写服务提供者
- 创建一个spring boot 工程
- maven依赖,与 eureka-server 一样
- 启动类增加 @EnableDiscoveryClient
就是意味着,这个项目是Eureka客户端服务,需要将自身信息注册到Eureka注册中心去
@EnableDiscoveryClient
@SpringBootApplication
public class Provider {
public static void main(String[] args) {
SpringApplication.run(Provider.class, args);
}
}
- 工程配置文件application.properties
spring.application.name=eureka-client-user-service
server.port=8081
# Eureka注册中心的地址。
eureka.client.serviceUrl.defaultZone=http:localhost:8761/eureka/
# 采用IP注册。
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
- 暴露接口
@RestController
public class UserController {
@GetMapping("/user/hello")
public String hello() {
return "hello";
}
}
编写服务消费者
- 创建一个spring boot 工程
- maven依赖,与 eureka-server 一样
- 启动类增加 @EnableDiscoveryClient
- 工程配置文件application.properties
spring.application.name=eureka-client-article-service
server.port=8082
# Eureka注册中心的地址。
eureka.client.serviceUrl.defaultZone=http:localhost:8761/eureka/
# 采用IP注册。
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
- 改造 RestTemplate,使可以用 服务名 调生产者。
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
主要是@LoadBalanced注解其实是在初始化 RestTemplate 这个bean的时候,加了个LoadBalancerInterceptor拦截器而已。然后在真实使用这个 RestTemplate 请求的时候,就会在拦截器中将 服务名 替换成真实请求的ip+port
- 通过Eureka调接口
@GetMapping("/article/callHello")
public String callHello() {
return restTemplate.getForObject("http://eureka-client-user-service/user/hello", String.class);
}
网友评论