一、使用Eureka
https://spring.io/projects/spring-cloud-netflix
1. 1搭建Eureka Server
创建工程导入依赖
父项目中pom
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR6</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
子项目中pom文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
SpringCloud和SpringBoot有版本契合要求,版本不匹配就会报错
配置application.yml
server:
port: 9003
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false #是否将自己注册到注册中心
fetch-registry: false #是否从eureka获取注册信息
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
配置启动类
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
浏览器访问:http://localhost:9003/
1.2将服务提供者注册到eurekaserver上
引入EurekaClient依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置EurekaClient信息 application.yml
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:9003/eureka/
1.3 在服务中调用
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/buy/{id}", method = RequestMethod.GET)
public Product findByid(@PathVariable Long id){
List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
if(instances == null && instances.size() == 0) {
return null;
}
ServiceInstance instance = instances.get(0);
Product product = restTemplate.getForObject("http://"+instance.getHost()+":"+instance.getPort()+"/product/"+id,Product.class);
return product;
}
}
2 Eureka的高可用性
2.1 搭建多个EurekaServer,相互注册。
server1:
spring:
application:
name: eureka-server
server:
port: 9000
eureka:
client:
service-url:
defaultZone: http://localhost:8000/eureka/
server2
spring:
application:
name: eureka-server
server:
port: 8000
eureka:
client:
service-url:
defaultZone: http://localhost:9000/eureka/
idea里面可以用用【command+D】复制一个配置,修改后启动多个实例。
启动后效果如下
2.2 将每个微服务都注册在EurekaServer上
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:9000/eureka/ , http://localhost:8000/eureka/