假设是OrderService里面拉取Eureka的服务之一User Service
1.依然需要在该服务里面引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.在OrderService里面需要有如下配置
spring:
application:
name: orderservice #添加的微服务的服务名称,把名字为userservice的微服务加入到注册名单中
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka #eureka的地址信息
3.修改URL和OrderService中添加@Load Balanced注解
1.修改URL
package cn.itcast.eureka.order.service;
import cn.itcast.eureka.order.mapper.OrderMapper;
import cn.itcast.eureka.order.pojo.Order;
import cn.itcast.eureka.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
String url = "http://userservice/user/" + order.getUserId();//OrderService里面拉取Eureka的服务之一User Service
//把原来的http://localhost:8080/user/变成了http://userservice/user/
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
// 4.返回
return order;
}
}
2.OrderService中添加@Load Balanced注解
package cn.itcast.eureka.order;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@MapperScan("cn.itcast")
@SpringBootApplication
public class OrderApplication {
@Bean @LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
通过服务名称获取IP地址的原理如下图所示,其中由于WIndows电脑的设置,原来的IP地址被替换成为了电脑名称LAPTOPXXX,其实还是可以获取到具体的IP