order-service服务通过服务名称来代替 ip:port的方式访问user-service服务的接口。
原来的请求代码:
@Service
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate RestTemplate restTemplate;@Overridepublic Order queryOrderById(Long orderId) {Order order = orderMapper.findById(orderId);String url = "http://localhost:8081/user/" + order.getUserId();User user = restTemplate.getForObject(url, User.class);order.setUser(user);return order;}
}
改造过后的代码:
1.添加负载均衡注解@LoadBalanced
@SpringBootApplication
@MapperScan("com.xkj.org.mapper")
public class OrderApplication {public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}
}
2.调用代码
@Service
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate RestTemplate restTemplate;@Overridepublic Order queryOrderById(Long orderId) {Order order = orderMapper.findById(orderId);String url = "http://user-service/user/" + order.getUserId();User user = restTemplate.getForObject(url, User.class);order.setUser(user);return order;}
}