微服务拆分和远程调用

SPringCloud对应的 boot版本

2020.0.x aka llford 2.4.x

Hoxton   2.2.x (SR5)  2.3.x(SR5以上)

Greenwich 2.1.x

Finchley 2.0x

Edgware 1.5.x

Dalston 1.5.x

服务拆分注意事项

1.微服务需要根据业务模块拆分做到单一职责,不同微服务,不能重复开服相同业务

2.微服务数据独立,不要访问其他微服务的数据库

3.微服务将自己的业务暴露为接口,供其他微服务调用

远程调用方式分析

1.注册RestTemplete

application类也是配置类,@Bean只能在配置类里

@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }

    /**
     * create by: csk
     * description: 创建RestTemplate并注入Spring容器
     * create time: 2021/9/18 15:49
     *
      * @Param: null
     * @return
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2.远程服务调用RestTemplate

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        //2.利用RestTemplate发起http请求,查询用户
        String  url = "http://localhost:8081/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);
        //3.封装user到order
        order.setUser(user);
        // 4.返回
        return order;
    }
}

微服务的调用方式

1.基于RestTemplate发起的http请求实现远程调用

2.http请求做远程调用与语言无关的调用,只要知道对方的ip 端口和接口路径请求参数即可。

posted @ 2021-09-18 16:09  zuiAI0658  阅读(133)  评论(0)    收藏  举报