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。
|