智能搜索 , 历史记录 , 用户量不太大的情况下 package com.collections.redis;import java.util.ArrayList;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Component;import redis.client
package com.collections.redis;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
/**
* 搜索历史记录
*
* @author Administrator
*/
@Component
public class SearchHistoryAndAutoMatchs {
@Resource
private Jedis redis;
/**
* 更新搜索历史列表
* @param userId 用户id
* @param searchkey 本次搜索关键词
*/
public void updateList(Integer userId, String searchkey) {
String key = "recent_search_" + userId;
// 为了保证事务和性能,采用pipeline
Pipeline pipeline = redis.pipelined();
pipeline.lrem(key, 1, searchkey);// 如果该关键词已存在先删除
pipeline.lpush(key, searchkey);// 把该关键词放在最顶部(左边)
pipeline.ltrim(key, 0, 4);// 裁剪list 保留最近的5个关键词
pipeline.sync();// 批量提交命令
}
/**
* 从搜索历史列表中获取匹配的列表
* @param userId
* @param pre
* @return
*/
public List
getAutoMatchs(Integer userId, String pre) {
String key = "recent_search_" + userId;
List
all = redis.lrange(key, 0, -1);// 获取该用户对应的“搜索历史列表” if (all == null) { return null; } if (pre != null && pre.length() > 0) { List
matchList = new ArrayList
(); for (String one : all) { // 前缀匹配 if (one.startsWith(pre)) { matchList.add(one); } } return matchList;// 返回匹配到的“搜索历史列表” } else { return all;// 用户还没有输入,就返回所有的“搜索历史列表” } } /** * 从词库列表中获取匹配的列表 * @param pre * @return */ public List
getDefaultAutoMatchs(String pre){ String key = "all_key_words"; List
all = redis.lrange(key,0,-1);//获取“关键词词库列表” if(all == null){ return null; } if(pre!=null && pre.length()>0){ List
matchList = new ArrayList
(); for(String one:all){ //前缀匹配 if(one.startsWith(pre)){ matchList.add(one); } } return matchList;//返回匹配到的“关键词词库列表” }else { return all;//用户还没有输入,就返回所有的“关键词词库列表” } } }
