SpringCloud 实现服务远程调用案例
一、创建RestTemplate的Bean
如:
package cn.itcast.order; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @MapperScan("cn.itcast.order.mapper") @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } //启动类本身也就是配置对象 /** * 创建RestTemplate对象并注入spring容器 */ @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
二、服务层里进行注入调用
package cn.itcast.order.service; import cn.itcast.order.mapper.OrderMapper; import cn.itcast.order.pojo.Order; import cn.itcast.order.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class OrderService { @Autowired private RestTemplate restTemplate; public Order queryOrderById(Long orderId) { // 1.查询订单 Order order = orderMapper.findById(orderId); //2.利用RestTemplate发起http请求,查询用户 //2.1 url路径 String url = "http://localhost:8081/user/" + order.getUserId(); //2.2发送http请求,实现远程调用 User user = restTemplate.getForObject(url, User.class); //3.封装user到Order order.setUser(user); // 4.返回 return order; } }
三、总结
在实现微服务调用时经常会出现联表查询的需求,此时我们可以考虑通过RestTemplate接口来实现服务端的请求发送,再将通过id请求到的数据合并到客户需求的数据里返回给客户。
实现流程图: