服务提供者:一次业务中,被其它微服务调用的服务。(提供接口给其它微服务)
服务消费者:一次业务中,调用其它微服务的服务。(调用其它微服务提供的接口)
作用:(1)避免在远程服务中,总是编写硬编码。(2)检查每个服务的正常情况。
服务端:eureka-server 客户端:其他服务(order-service,user-service)

引入eureka-server依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>
spring-cloud-starter-netflix-eureka-server
</artifactId>
</dependency>
添加@EnableEurekaServer注解
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
在application.yml中配置eureka地址
server:
port: 10086
spring:
application:
name: eureka-service
eureka:
client:
service-url:
defaultZone: <http://127.0.0.1:10086/>
register-with-eureka: false
fetch-registry: false
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
spring:
application:
name: userservice
eureka:
client:
service-url:
defaultZone: <http://127.0.0.1:10086/eureka>
首先先把服务提供者进行注册
@LoadBalanced注解(无论需不需要负载均衡都要添加)@GetMapping("{orderId}")
public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
// 根据id查询订单并返回
Order order = orderService.queryOrderById(orderId);
// 远程服务调用
String url = "<http://userservice/user/>" + order.getUserId();
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}