-
userQueryServicepublic interface UserQueryService { public Map<Long, UserDTO> queryUserMap(List<? extends UserIdFunction> list); }
-
public interface UserIdFunction { Long getUserId(); }
-
获取userId的复用代码
主义泛型参数
@Slf4j @Service public class UserQueryServiceImpl implements UserQueryService { @Autowired private UserClient userClient; @Override public Map<Long, UserDTO> queryUserMap(List<? extends UserIdFunction> list) { List<Long> userIds = list.stream().map(UserIdFunction::getUserId).distinct().collect(Collectors.toList()); List<UserDTO> users = userClient.queryUserByIds(userIds); if (CollUtils.isEmpty(users)) { log.info("查询不到用户信息:{}", userIds); throw new BizIllegalException("网络异常"); } Map<Long, UserDTO> userMap = users.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity())); return CollUtils.isEmpty(userMap) ? new HashMap<>() : userMap; } }
-
使用的时候,先注入userQueryService,让boardList中的实体类继承UserIdFunction
Map<Long, UserDTO> userMap = userQueryService.queryUserMap(boardList);