使用redis的缓存功能 (windows 版redis)

需要用到的jar:

  commons-pool2-2.3.jar
  jedis-2.7.0.jar

JedisPoolConfig的配置文件redis.properties

redis.maxIdle=30
redis.minIdle=10
redis.maxTotal=100
redis.url=localhost
redis.port=6379

redis数据库连接的连接池工具类JedisPoolUtils

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisPoolUtils {
    
    private static JedisPool pool = null;
    
    static{
        
        //加载配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        //获得池子对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));//最大闲置个数
        poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));//最小闲置个数
        poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));//最大连接数
        pool = new JedisPool(poolConfig,pro.getProperty("redis.url") , Integer.parseInt(pro.get("redis.port").toString()));
    }

    //获得jedis资源的方法
    public static Jedis getJedis(){
        return pool.getResource();
    }
    
    public static void main(String[] args) {
        Jedis jedis = getJedis();
        System.out.println(jedis.get("xxx"));
    }

}

redis使用:

//先从缓存中查询categoryList 如果有直接使用 没有在从数据库中查询 存到缓存中
//1.获得jedis对象 连接redis数据库
Jedis jedis = JedisPoolUtils.getJedis();
String categoryListJson = jedis.get("categoryListJson");
//2.判断categoryListJson是否为空
if(categoryListJson == null){
    System.out.println("缓存没有数据 查询数据库");
    //准备分类数据 从数据库中查询
    List<Category> categoryList = service.findAllCategory();
    Gson gson = new Gson();
    categoryListJson = gson.toJson(categoryList);
  //将查询出来的数据放到redis数据库中
    jedis.set("categoryListJson", categoryListJson); 
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(categoryListJson);
原文地址:https://www.cnblogs.com/ms-grf/p/7204097.html