OpenFeign实现服务发现远程调用以及负载均衡-SpringCloudAlibaba No.2

Posted Fire king

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了OpenFeign实现服务发现远程调用以及负载均衡-SpringCloudAlibaba No.2相关的知识,希望对你有一定的参考价值。

OpenFeign实现服务发现远程调用以及负载均衡

1.导入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 这里需要单独导入LoadBalancer依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

2.编写接口(@FeignClient和@EnableFeignClients):

2.1.借阅类

注意:@FeignClient的值userservice和bookservice需要在对应服务的配置文件配置服务名称且一一对应,我们在nacos那一篇已经配置过了:传送门

@FeignClient("userservice")
public interface UserClient 

    @RequestMapping("/user/uid")
    User getUserById(@PathVariable("uid") int uid);

@FeignClient("bookservice")
public interface BookClient 

    @RequestMapping("/book/bid")
    Book getBookById(@PathVariable("bid") int bid);

@Service
public class BorrowServiceImpl implements BorrowService

    @Resource
    BorrowMapper mapper;

    @Resource
    UserClient userClient;

    @Resource
    BookClient bookClient;

    @Override
    public UserBorrowDetail getUserBorrowDetailByUid(int uid) 
        List<Borrow> borrow = mapper.getBorrowsByUid(uid);
        User user = userClient.getUserById(uid);
        List<Book> bookList = borrow
                .stream()
                .map(b -> bookClient.getBookById(b.getBid()))
                .collect(Collectors.toList());
        return new UserBorrowDetail(user, bookList);
    

注意:加@EnableFeignClients才能是配置生效

@EnableFeignClients
@SpringBootApplication
public class BorrowApplication 
    public static void main(String[] args) 
        SpringApplication.run(BorrowApplication.class, args);
    

2.2.图书类和用户类

图书类:

@RestController
public class BookController 

    @Resource
    BookService service;

    @RequestMapping("/book/bid")
    Book findBookById(@PathVariable("bid") int bid,
                      HttpServletRequest request)
        System.out.println(request.getHeader("Test"));
        return service.getBookById(bid);
    

用户类:

@RestController
public class UserController 

    @Resource
    UserService service;

    @RequestMapping("/user/uid")
    public User findUserById(@PathVariable("uid") int uid)
        System.out.println("我被调用拉!");
        return service.getUserById(uid);
    

3.可能出现的bug

如果出现RestTemplate字眼的bug,需要注册RestTemplate的bean。

以上是关于OpenFeign实现服务发现远程调用以及负载均衡-SpringCloudAlibaba No.2的主要内容,如果未能解决你的问题,请参考以下文章

SpringCloud远程调用-OpenFeign

springcloud—— eureka本地集群搭建以及实现微服务的负载均衡调用

微服务实战|声明式服务调用OpenFeign实践

PassJava 开源 : 整合 OpenFeign实现声明式远程调用 #私藏项目实操分享#

SpringCloud开发指南——Ribbon和OpenFeign服务调用

微服务之——负载均衡和服务接口调用(Ribbonopenfeign)