<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
导入Eureka服务端依赖,建立注册中心

配置注册中心

  1. #设置Eureka端口
  2. server:
  3. port: 8081
  4. # 应用名称/服务名
  5. spring:
  6. application:
  7. name: eurekaserver
  8. eureka:
  9. client:
  10. #false表示不向注册中心注册自己
  11. register-with-eureka: false
  12. #false表示自己端就是注册中心,我的职责就是维护实例,并不需要去检索服务
  13. fetch-registry: false
  14. #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
  15. service-url:
  16. defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  17. #eureka服务端的实例名称
  18. instance:
  19. hostname: localhost

添加@EnableEurekaServer注解到springboot项目启动类

表示此模块是注册中心
启动服务
在网页输入:http://localhost:10086/进入注册中心
服务列表参数
image.png

配置Eureka客户端


<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

配置服务注册信息

服务注册

  1. #设置Eureka端口
  2. server:
  3. port: 6666
  4. # 应用名称/服务名
  5. spring:
  6. application:
  7. name: eurekaorder
  8. eureka:
  9. client:
  10. #表示是否将自己注册进Eureka,默认为true
  11. register-with-eureka: true
  12. #是否从EurekaServer抓取已有的注册信息,默认为true
  13. fetch-registry: true
  14. #向服务注册中心注册自己(此处为注册中心地址)
  15. service-url:
  16. defaultZone: http://localhost:10086/eureka/
  17. instance:
  18. #更改主机实例ID名
  19. instance-id: ${spring.application.name}:${server.port}
  20. #鼠标悬停时显示主机ip地址
  21. prefer-ip-address: true

添加@EnableEurekaClient注解到springboot项目启动类

将模块注册成服务

idea如何显示springboot多服务启动状况

实现服务多实例

image.png
-Dserver.port=8082
image.png

跨服务的远程调用

在启动类中创建RestTemplate对象注入ioc容器中

  1. //使用RestTemplate实现跨服务的远程调用
  2. //向其他服务发送HTTP请求
  3. @Bean
  4. @LoadBalanced//负载均衡注解
  5. public RestTemplate restTemplate(){
  6. return new RestTemplate();
  7. }

服务拉取

  1. @RestController
  2. public class OrderController {
  3. @Autowired
  4. private RestTemplate restTemplate;
  5. @GetMapping("/order")
  6. public String hello(){
  7. //url=user服务的服务名/应用名称+请求路径
  8. String url="http://eurekuser/user";
  9. /**
  10. * 发布http请求实现远程调用
  11. * 参数1:跨服务的请求路径
  12. * 参数2:返回值类型
  13. */
  14. String user = restTemplate.getForObject(url, String.class);
  15. return "hellorder"+user;
  16. }
  17. }

Eureka@LoadBalanced负载均衡

服务中心的流程

image.png