zoukankan      html  css  js  c++  java
  • 使用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);
  • 相关阅读:
    当期所得税费用总额
    所得税净利润算法
    [AGC028B]Removing Blocks 概率与期望
    bzoj 4319: cerc2008 Suffix reconstruction 贪心
    bzoj 2430: [Poi2003]Chocolate 贪心
    BZOJ 2839: 集合计数 广义容斥
    luogu 5505 [JSOI2011]分特产 广义容斥
    CF504E Misha and LCP on Tree 后缀自动机+树链剖分+倍增
    CF798D Mike and distribution 贪心
    CF707D Persistent Bookcase 可持久化线段树
  • 原文地址:https://www.cnblogs.com/ms-grf/p/7204097.html
Copyright © 2011-2022 走看看