• [Spring cloud 一步步实现广告系统] 10. 使用Ribbon 实现微服务调用


    在使用Ribbon调用广告投放系统API之前,我们需要先创建2个VO对象,AdPlanVO,AdPlanGetRequestVO.

    //数据请求对象
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class AdPlanGetRequestVO {
        private Long userId;
        private List<Long> planIds;
    }
    
    ----------------------------------
     
    //API请求响应结果反序列化对象
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class AdPlanVO {
        private Long planId;
        private Long userId;
        private String planName;
        private Integer planStatus;
        private Date startDate;
        private Date endDate;
        private Date createTime;
        private Date updateTime;
    }
    

    AdSearchApplication启动类中,添加RestTemplate客户端。

    public class AdSearchApplication {
      ...
        /**
         * 注册{@link RestTemplate}Bean
         * @return
         */
        @Bean
        @LoadBalanced //让RestTemplate在调用服务的时候,可以实现负载均衡
        RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    

    创建一个controller,来测试调用广告提供系统的API

    /**
     * SearchController for search information controller
     *
     * @author <a href="mailto:magicianisaac@gmail.com">Isaac.Zhang | 若初</a>
     */
    @RestController
    @Slf4j
    @RequestMapping(path = "/search")
    public class SearchController {
      	//注入RestTemplate
        private final RestTemplate restTemplate;
        @Autowired
        public SearchController(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }
    
        @GetMapping(path = "/plan/get-ribbon")
        public CommonResponse<List<AdPlanVO>> getAdPlansUseRibbon(@RequestBody AdPlanGetRequestVO requestVO) {
            log.info("ad-search::getAdPlansUseRibbon -> {}", JSON.toJSONString(requestVO));
            return restTemplate.postForEntity(
                    "http://mscx-ad-sponsor/ad-sponsor/plan/get", requestVO, CommonResponse.class
            ).getBody();
        }
    
        @GetMapping(path = "/user/get")
        public CommonResponse getUsers(@Param(value = "username") String username) {
            log.info("ad-search::getUsers -> {}", JSON.toJSONString(username));
            CommonResponse commonResponse = restTemplate.getForObject(
                    "http://mscx-ad-sponsor/ad-sponsor/user/get?username={username}", CommonResponse.class, username
            );
            return commonResponse;
        }
    }
    
  • 相关阅读:
    各种blog尝试后,发现wordpress适用起来最方便
    索引器(C# 编程指南)
    vue3 父子组件之间的传值
    vue3 + vite + ts 搭建项目
    vue3中使用全局变量
    用JSONKit库解析json文件
    程序内部让用户直接上appstore评价游戏的链接地址以及跳转方法
    常见错误:Apple MachO Linker Error
    常见错误:多线程界面元素显示错误
    常见错误:Undefined symbols for architecture i386
  • 原文地址:https://www.cnblogs.com/zhangpan1244/p/11279177.html
Copyright © 2020-2023  润新知