QuestionQueryApi.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package nju.seec.helper.api.bok;
  2. import com.google.common.collect.ImmutableMap;
  3. import com.google.common.collect.Lists;
  4. import com.google.common.collect.Maps;
  5. import com.google.gson.reflect.TypeToken;
  6. import lombok.Data;
  7. import nju.seec.helper.api.bok.vo.QuestionVO;
  8. import nju.seec.helper.util.JsonUtils;
  9. import nju.seec.helper.util.RestRequestUtil;
  10. import nju.seec.helper.util.cache.CaffeineCacheUtils;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.boot.context.properties.ConfigurationProperties;
  13. import org.springframework.stereotype.Component;
  14. import java.util.List;
  15. import java.util.Map;
  16. import java.util.stream.Collectors;
  17. /**
  18. * @author cst
  19. */
  20. @Component
  21. @ConfigurationProperties("bok.question-query")
  22. @Data
  23. public class QuestionQueryApi {
  24. @Value("${bok.question-cache-name}")
  25. private String bokQuestionCacheName;
  26. private final RestRequestUtil restRequestUtil;
  27. private final CaffeineCacheUtils cacheUtils;
  28. private String byIdUrl;
  29. public QuestionQueryApi(RestRequestUtil restRequestUtil, CaffeineCacheUtils cacheUtils) {
  30. this.restRequestUtil = restRequestUtil;
  31. this.cacheUtils = cacheUtils;
  32. }
  33. @SuppressWarnings({"unchecked", "rawtypes"})
  34. public List<QuestionVO> getQuestionListById(final List<String> ids) {
  35. Map<String, QuestionVO> bokQuestionsMap = Maps.newHashMapWithExpectedSize(ids.size());
  36. final Map<String, QuestionVO> cacheBokQuestionsMap = (Map) cacheUtils.multiGet(bokQuestionCacheName, ids);
  37. bokQuestionsMap.putAll(cacheBokQuestionsMap);
  38. List<String> requestIds = Lists.newArrayList(ids);
  39. requestIds.removeAll(cacheBokQuestionsMap.keySet());
  40. //未缓存的去这里拿
  41. if (!requestIds.isEmpty()) {
  42. Map<String, String> uriVariables = ImmutableMap.of("id", requestIds.stream().reduce((a, b) -> a + "," + b).orElse(""));
  43. List<QuestionVO> questionVOList = JsonUtils.fromJson(restRequestUtil.sendGetRequest(byIdUrl, String.class, uriVariables), new TypeToken<List<QuestionVO>>() {
  44. });
  45. Map<String, QuestionVO> remoteBokQuestionsMap = questionVOList.parallelStream().collect(Collectors.toMap(QuestionVO::getId, bokQuestion -> bokQuestion));
  46. bokQuestionsMap.putAll(remoteBokQuestionsMap);
  47. cacheUtils.setAll(bokQuestionCacheName, (Map) remoteBokQuestionsMap);
  48. }
  49. return ids.stream()
  50. .map(bokQuestionsMap::get)
  51. .collect(Collectors.toList());
  52. }
  53. }