[Spring cloud step by step implementation of the ad system] 10. Use Ribbon implement micro-call service

Before using the Ribbon call advertising system API, we need to create two VO objects 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;
}

In the AdSearchApplicationstartup class, add RestTemplatethe client.

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

Create a controller, to test the API call ad serving system

/**
 * SearchController for search information controller
 *
 * @author <a href="mailto:[email protected]">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;
    }
}

Guess you like

Origin blog.51cto.com/1917331/2425421