微服务结构及微服务远程调用

目录

一、微服务结构

二、微服务远程调用


一、微服务结构

        微服务这种方案需要技术框架来落地,全球的互联网公司都在积极尝试自己的微服务落地技术。在国内最知名的就是SpringCloud和阿里巴巴的Dubbo

 微服务技术对比:

Dubbo SpringCloud SpringCloudAlibaba
注册中心 zookeeper、Redis Eureka、Consul Nacos、Eureka
服务远程调用 Dubbo协议 Feign (http协议) Dubbo、Feign
配置中心 SpringCloudfig SpringCloudfig、Nacos
服务网关 SpringCloudGateway、Zuul SpringCloudGateway、Zuul
服务监控保护 dubbo-admin、功能弱 Hystix Sentinel

二、微服务远程调用

根据订单id查询订单功能:

需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回

 实现步骤:

1、注册RestTemplate

order-serviceOrderApplication中注册RestTemplate

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

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

    /**
     * 创建RestTemplate并注入Spring容器
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2、服务远程调用RestTemplate

修改order-service中的OrderServicequeryOrderById方法:

@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,查询用户
        //2.1 url路径
        String url = "http://localhost:8081/user/"+order.getUserId();
        //2。1 发送http请求,实现远程调用
        User user = restTemplate.getForObject(url,User.class);
        //3.封装user到Order
        order.setUser(user);
        // 4.返回
        return order;
    }
}

微服务调用方式:

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

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

提供者及消费者:

服务提供者:一次业务中,被其他微服务调用的服务(提供接口给其他微服务)

服务消费者:一次业务中,调用其他微服务的服务 (调用其他的微服务提供的接口)

服务调用关系:

服务提供者:暴露接口给其他微服务调用

服务消费者:调用其他微服务提供的接口

提供者与消费者角色是相对

一个服务可以同时是服务提供者和服务消费者

猜你喜欢

转载自blog.csdn.net/m0_61961937/article/details/127712139