eureka
一、Eureka原理分析
1.1 服务调用出现的问题
1.2 Eureka的作用
- 服务消费者该如何获取服务提供者的地址信息?
- 如果有多个服务提供者,消费者该如何选择?
- 消费者如何得知服务提供者的健康状态?
二、 搭建Eureka
2.1 创建项目
- 选择Maven:
- 在pom.xml中添加Eureka的依赖,添加SpringBoot的启动依赖
<dependencies>
<!--eureka服务端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.2 编写启动类,添加@EnableEurekaServer注解
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
2.3 添加application.yml的配置文件
server:
port: 10086
spring:
application:
name: eurekaserver # eureka服务名称
eureka:
client:
service-url: # eureka地址信息
defaultZone: http://localhost:10086/eureka
2.4 注册服务到Eureka
- 将一个服务注册到EurekaServer步骤如下:
2.4.1 在服务项目中引入eureka客户端依赖
<!--eureka客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.4.2 配置application.yml文件的信息
spring:
datasource:
url: jdbc:mysql://localhost:3306/cloud_user?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
application:
name: userservice # user服务的服务名称
eureka:
client:
service-url: #eureka地址信息
defaultZone: http://localhost:10086/eureka
2.4.3 模拟多实例部署
- 在idea中选择一个部署好Eureka的模块,右键选择Copy Configuration
- 自定义一个名字:
- 配置与原模块不同的端口号,点击Environment,在VM options中修改端口
-Dserver.port=新端口号
:
2.5 服务发现
2.5.1 在order-service完成服务拉取
- 服务拉取是基于服务名称获取服务列表,然后在对服务列表做负载均衡
- 修改OrderService的代码,修改访问的url路径,用服务名代替ip、端口:
//2.利用RestTemplate发起http请求,查询用户
String url = "http://userservice/user/" + order.getUserId();
2.5.2 在order-service顶目的启动类Orderapplication中的RestTemplate添加负载均衡注解
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}