目的:将用户搜索的关键词保存到redis中,且只显示最近的8条,在redis中,key的格式是HISTORY+用户的id
实现方式:使用单键多值的列表实现
具体代码
package com.cy.store.util;
import com.cy.store.common.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.Jedis;
import java.util.List;
public class SearchHistoryUtil {
public static void saveSearchHistory(Integer uid, String searchTerm) {
String saveKey = Const.HISTORY_K + uid.toString();
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.lrem(saveKey, 0, searchTerm);
jedis.lpush(saveKey,searchTerm);
jedis.ltrim(saveKey, 0, 7);
}
public static List<String> getSearchHistory(Integer uid) {
String saveKey = Const.HISTORY_K + uid.toString();
List<String> list;
Jedis jedis = new Jedis("127.0.0.1",6379);
list = jedis.lrange(saveKey, 0, 7);
return list;
}
public static void removeSearchHistory(Integer uid) {
String saveKey = Const.HISTORY_K + uid.toString();
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.del(saveKey);
}
}
测试增加搜索历史:虽然增加了九条,但是只保存了就近的八条
@Test
public void test2() {
SearchHistoryUtil.saveSearchHistory(7, "java");
SearchHistoryUtil.saveSearchHistory(7, "c++");
SearchHistoryUtil.saveSearchHistory(7, "java web");
SearchHistoryUtil.saveSearchHistory(7, "python");
SearchHistoryUtil.saveSearchHistory(7, "c#");
SearchHistoryUtil.saveSearchHistory(7, "c");
SearchHistoryUtil.saveSearchHistory(7, "scala");
SearchHistoryUtil.saveSearchHistory(7, "spark");
SearchHistoryUtil.saveSearchHistory(7, "Vue");
}
获取、删除搜索记录就不测试了,传用户id即可