要求:
1.限制搜索历史的个数
2.大于三十天清除历史纪录
3.最多5条历史纪录
代码:
第一部分:查询接口
@PostMapping("/getAiResults") @SneakyThrows public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception { try { String encode = Base64.encode(file.getBytes()); ImageRequest imageRequest = new ImageRequest(); imageRequest.setImage(encode); String result = EasydlImageClassify.easydlImageClassify(imageRequest); AiResponseEntity jsonObject = JSONUtil.toBean(result, AiResponseEntity.class); HashMap<String, InsectEntity> dataMap = new HashMap<String, InsectEntity>(); List<InsectEntity> results = jsonObject.getResults(); results.forEach(item -> { InsectEntity ins = dataMap.get(item.getName()); if (ins != null) { dataMap.put(item.getName(), item.getScore() > ins.getScore() ? item : ins); } else { dataMap.put(item.getName(), item); } }); Set<String> strings = dataMap.keySet(); ArrayList<InsectEntity> insectEntities = new ArrayList<>(); strings.forEach(item -> { insectEntities.add(dataMap.get(item)); }); insectEntities.forEach(item -> { SituationArchivesPests one = situationArchivesPestsService.getOne(Wrappers.lambdaQuery(SituationArchivesPests.class) .eq(SituationArchivesPests::getInsectName, item.getName())); item.setPests(one); // ==============================核心代码 String key = RedisKeyPrefix.农情快讯搜索.getKey() + SecurityUtils.getLoginUser().getUser().getUserId(); redisTemplate.expire(key, 30, TimeUnit.DAYS); // if (one!=null){ redisTemplate.opsForList().leftPush(key, JSONUtil.toJsonStr(item)); Long size = redisTemplate.opsForList().size(key); if (size > 10) { redisTemplate.opsForList().rightPop(key); } // } //===============================核心代码 }); return AjaxResult.success(insectEntities); } catch (Exception e) { return AjaxResult.error(e.getMessage()); } }
第一部分:获取历史
@GetMapping(value = "/serarchHistory") @ApiOperation("识虫历史记录") public AjaxResult serarchHistory() { String key = RedisKeyPrefix.识虫历史记录.getKey() + SecurityUtils.getLoginUser().getUser().getUserId(); Long size = redisTemplate.opsForList().size(key); List<String> range = redisTemplate.opsForList().range(key, 0, size - 1); return AjaxResult.success(range);