例如: 查询小明借阅的图书列表
借阅信息数据库为
id:1 uid: 1 bid:1
id:2 uid: 1 bid:3
我们需要把
uid的1 变成小明
bid的1和3 变成两本书籍的信息
这就需要 template 来进行远程调用
User user = template.getForObject("http://localhost:8101/user/"+uid, User.class);
这样就可以远程调用接收User对象了
List<Book> bookList = borrow
.stream()
.map(b -> template.getForObject("http://localhost:8201/book/"+b.getBid(), Book.class))
.collect(Collectors.toList());
这样就可以获取书籍的list集合了
return new UserBorrowDetail(user, bookList);
然后返回数据就可以了
实体类是这样的:
@Data
@AllArgsConstructor
public class UserBorrowDetail {
User user;
List<Book> bookList;
}
关于template的完整代码,template可以配置在config包中
@Configuration
public class BeanConfig {
@Bean
//可以给template类配制负载均衡
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在ServiceImpl中具体使用
@Service
public class BorrowServiceImpl implements BorrowService {
@Resource
BorrowMapper mapper;
@Autowired
RestTemplate template;
@Override
public UserBorrowDetail getUserBorrowDetailByUid(int uid) {
List<Borrow> borrow = mapper.getBorrowsByUid(uid);
//RestTemplate支持多种方式的远程调用
//这里通过调用getForObject来请求其他服务,并将结果自动进行封装
//获取User信息
User user = template.getForObject("http://userservice/user/"+uid, User.class);
//获取每一本书的详细信息
List<Book> bookList = borrow
.stream()
.map(b -> template.getForObject("http://bookservice/book/"+b.getBid(), Book.class))
.collect(Collectors.toList());
return new UserBorrowDetail(user, bookList);
}
}
标签: spring springcloud
推荐阅读:
vue.js:634 [Vue warn]: Property or method "userName" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See:
状态码:415,发送HTTP请求返回415状态码的解决办法
SpringBoot 整合 webapp时 访问404的解决办法
Vue 打开页面时就加载方法,例如查询
Spring整合Mybatis
SpringCloud 加入 thymleaf前端页面的方法
Controller之间的跳转
Spring AOP的实现原理
This may be the result of an unspecified view, due to default view name generation
给idea添加thymleaf模板
Seek respect, not attention.