spring-cloud整合 Ribbon

一.加依赖

发现,spring-cloud-starter-alibaba-nacos-discovery 已经加了Ribbon的依赖,所以我们不用再加Ribbon的依赖了。
在这里插入图片描述

二、加配置

Ribbon 不需要在yml配置,所以yml也不用改。

三、加注解

//扫描哪些包里的接口
@MapperScan("com.itmuch")
@SpringBootApplication
public class ContentCenterApplication {

    public static void main(String[] args) {


        SpringApplication.run(ContentCenterApplication.class, args);
    }
    @Bean
    @LoadBalanced //加Ribbon注解
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

四、写代码

public class ShareService {

    private final ShareMapper shareMapper;
    private final RestTemplate restTemplate;

    public ShareDTO findById(Integer id) {
        // 获取分享详情
        Share share = this.shareMapper.selectByPrimaryKey(id);
        //share里没有用户的信息,所以要调用user服务来获取
        Integer userId = share.getUserId();


        //"http://user-center/users/{userId}" Ribbon 会将 "user-center" 转化为 user-center 在Nacos上的地址,并实现负载均衡
        UserDTO userDTO = restTemplate.getForObject("http://user-center/users/{userId}",UserDTO.class,userId);
        ShareDTO shareDTO = new ShareDTO();
        BeanUtils.copyProperties(share,userDTO);
        shareDTO.setWxNickname(userDTO.getWxNickname());
        return shareDTO;
    }
}

版权声明:本文为Tiny_Demon原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。