美文网首页
day01 :服务提供者与消费者

day01 :服务提供者与消费者

作者: 城南码农 | 来源:发表于2018-03-06 22:52 被阅读0次

    记住两个概念
    1 springboot 提供了快速创建spring项目的脚手架,spring全家桶以插件的形式添加依赖
    2 springcloud提供了微服务的实现,包含rpc,容错隔离,负载等分布式系统需要的所有实现

    服务提供者:
    spring boot应用,支持http请求访问.部署在8081端口

    @RestController
    public class UserController {
    
        // 组合注解  相当于RequestMapping get请求方式
        @GetMapping("/user/{id}")
        public Long findById(@PathVariable Long id){
            return id+100;
        }
    }
    

    服务消费者:
    部署在8080端口

    // 这个bean这暂时需要手动new出来
    @Autowired
        private RestTemplate restTemplate;
    
        @RequestMapping("/hello/{id}")
        public Long findById(@PathVariable Long id) {
            Long forObject = restTemplate.getForObject("http://localhost:8081/user/" + id, long.class);
            return 1L;
        }
    

    在服务消费者启动时new出bean来

    // bean 注解 会 实例化一个bean  并且以方法名命名
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    

    问题:
    服务消费者的地址硬编码:http://localhost:8081/user/

    • 解决办法1:
      提取到web服务的配置文件中
      遗留问题:当此消费者作为另外的服务提供者时就会出现混乱。另外,有多个服务提供者的负载均衡问题。
     @Value("${userServicePath}")
      private String userServicePath;
    
    • 解决办法2:
      服务发现:包括zookeeper,consul,eureka
      详见下一节

    相关文章

      网友评论

          本文标题:day01 :服务提供者与消费者

          本文链接:https://www.haomeiwen.com/subject/afnrfftx.html