package nju.seec.helper.api.bok; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.reflect.TypeToken; import lombok.Data; import nju.seec.helper.api.bok.vo.QuestionVO; import nju.seec.helper.util.JsonUtils; import nju.seec.helper.util.RestRequestUtil; import nju.seec.helper.util.cache.CaffeineCacheUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author cst */ @Component @ConfigurationProperties("bok.question-query") @Data public class QuestionQueryApi { @Value("${bok.question-cache-name}") private String bokQuestionCacheName; private final RestRequestUtil restRequestUtil; private final CaffeineCacheUtils cacheUtils; private String byIdUrl; public QuestionQueryApi(RestRequestUtil restRequestUtil, CaffeineCacheUtils cacheUtils) { this.restRequestUtil = restRequestUtil; this.cacheUtils = cacheUtils; } @SuppressWarnings({"unchecked", "rawtypes"}) public List getQuestionListById(final List ids) { Map bokQuestionsMap = Maps.newHashMapWithExpectedSize(ids.size()); final Map cacheBokQuestionsMap = (Map) cacheUtils.multiGet(bokQuestionCacheName, ids); bokQuestionsMap.putAll(cacheBokQuestionsMap); List requestIds = Lists.newArrayList(ids); requestIds.removeAll(cacheBokQuestionsMap.keySet()); //未缓存的去这里拿 if (!requestIds.isEmpty()) { Map uriVariables = ImmutableMap.of("id", requestIds.stream().reduce((a, b) -> a + "," + b).orElse("")); List questionVOList = JsonUtils.fromJson(restRequestUtil.sendGetRequest(byIdUrl, String.class, uriVariables), new TypeToken>() { }); Map remoteBokQuestionsMap = questionVOList.parallelStream().collect(Collectors.toMap(QuestionVO::getId, bokQuestion -> bokQuestion)); bokQuestionsMap.putAll(remoteBokQuestionsMap); cacheUtils.setAll(bokQuestionCacheName, (Map) remoteBokQuestionsMap); } return ids.stream() .map(bokQuestionsMap::get) .collect(Collectors.toList()); } }