SpringCloud入门_认识微服务

1 什么是微服务

image

2 什么是微服务总结

image

3 微服务远程调用

1)注册RestTemplate

在order-service的OrderApplication中注册RestTemplate

@MapperScan("cn.itcast.order.mapper")  
@SpringBootApplication  
public class OrderApplication {  
  
    public static void main(String[] args) {  
        SpringApplication.run(OrderApplication.class, args);  
    }  
  
    @Bean  
    public RestTemplate restTemplate(){  
        return new RestTemplate();  
    }  
}

2)服务远程调用RestTemplate

修改order-service中的OrderService的queryOrderById方法:

@Service  
public class OrderService {  
  
    @Autowired  
    private OrderMapper orderMapper;  
  
    @Autowired  
    private RestTemplate restTemplate;  
  
    public Order queryOrderById(Long orderId) {  
        // 1.查询订单  
        Order order = orderMapper.findById(orderId);  
        // 2.生成url  
        String url = "http://localhost:8081/user/"+order.getUserId();  
        // 3.发请求到用户模块查询用户信息  
        User user = restTemplate.getForObject(url, User.class);  
        // 4.将查询到的用户数据添加到订单数据中  
        order.setUser(user);  
        // 5.返回  
        return order;  
    }  
}

3)微服务远程调用总结

微服务调用方式

》基于RestTemplate发起的http请求实现远程调用
》http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可。

posted @ 2022-07-09 09:11  烛火中的乌托邦  阅读(35)  评论(0)    收藏  举报