1.对于一些要经常访问的数据且不会改变的数据,那么就可以使用redis来缓存这些数据
2.可以使用JedisUtil来优化设计jedis的每次创建代码.
/**
* Jedis工具类
*/
public final class JedisUtil {
private static JedisPool jedisPool;
static {
//读取配置文件
InputStream is = JedisPool.class.getClassLoader().getResourceAsStream("jedis.properties");
//创建Properties对象
Properties pro = new Properties();
//关联文件
try {
pro.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取数据,设置到JedisPoolConfig中
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(Integer.parseInt(pro.getProperty("maxTotal")));
config.setMaxIdle(Integer.parseInt(pro.getProperty("maxIdle")));
//初始化JedisPool
jedisPool = new JedisPool(config, pro.getProperty("host"), Integer.parseInt(pro.getProperty("port")));
}
/**
* 获取连接方法
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
/**
* 关闭Jedis
*/
public static void close(Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
3.第一次使用Jedis来存入一个list列表到sortested
@Override
public List<Category> findAll() {
//创建redis
Jedis jedis = JedisUtil.getJedis();
Set<String> categoryNameStr= jedis.zrange("category", 0, -1);
List<Category> listCategory=null;
//如果是第一次查询不存在就传入redis
if (categoryNameStr==null&&categoryNameStr.size()==0){
//查询道列表
listCategory = categoryDao.findAll();
//存入redis:sortedset排序集合,
for (Category category : listCategory) {
jedis.zadd("category",category.getCid(),category.getCname());
}
}else {
//如果存在,那么就从redis中取出来直接使用,就不要再去查询数据库了
Category category=new Category();
for (String s : categoryNameStr) {
category.setCname(s);
listCategory.add(category);
}
}
return listCategory;
}