文章目录
Feign 使用步骤
加入openfeign 依赖配置
1 2 3 4 |
<dependency> <groupId>org.springframework.cloud</groupId> </dependency> |
给启动类加入注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@SpringBootApplication @EnableFeignClients // 启动 Feign public class ContentCenterApplication { public static void main(String[] args) { SpringApplication.run(ContentCenterApplication.class, args); } /** * 在容器中创建一个对象 RestTemplate类型 名称就是ID * @return */ @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } } |
配置feign 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * 声明式 http 客户端 name 表示的请求的应用 * feign 请求 user-center 应用服务 * http://user-center/users/{id} * @param id * @return */ @FeignClient(name = "user-center") public interface UserCenterFeignClient { @GetMapping("/users/{id}") UserDTO findById(@PathVariable Integer id); } |
应用中使用 feign
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
@Service @Slf4j public class ShareService { @Resource private ShareMapper shareMapper; @Autowired private UserCenterFeignClient userCenterFeignClient; // 注入feign Client public ShareDTO findById(Integer id) { Share share = shareMapper.selectByPrimaryKey(id); log.info(share.toString()); Integer userId = share.getUserId(); log.info("userId {}", userId); Integer userId = share.getUserId(); // 使用 feign 请求其他应用,应用名称在接口处已经指定为 user-center UserDTO userDTO = userCenterFeignClient.findById(userId); log.info(userDTO.toString()); ShareDTO shareDTO = new ShareDTO(); BeanUtils.copyProperties(share, shareDTO); shareDTO.setWxNickname(userDTO.getWxNickname()); return shareDTO; } |
对比 Ribbon Feign 其实很简单了,还在用 Rebbin 的可以试试Feign