jedispool是什么_redis工具类

jedispool是什么_redis工具类项目中需要用到缓存减少数据库压力,选择redis作为工具,构建一个jedis池达到实际效果11.JedisPoolCacheUtils<!–https://mvnrepository.com/artifact/redis.clients/jedis引入pom–><dependency><groupId&g…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

项目中需要用到缓存减少数据库压力,选择redis作为工具,构建一个jedis池达到实际效果
1
1.JedisPoolCacheUtils<!– https://mvnrepository.com/artifact/redis.clients/jedis  引入pom –>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
 

package com.ithzk.common.redis;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ithzk.common.util.Detect;
import com.ithzk.common.util.JsonUtil;
import com.ithzk.common.util.PropertiesUtil;

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

/**
 * redis 操作数据库配置类
 * @author huzekun
 * @date:2017年12月27日 下午3:01:04
 */
@Component("JedisPoolCacheUtils")
public class JedisPoolCacheUtils {

    private final static Logger log = Logger.getLogger(JedisPoolCacheUtils.class);

    public final static String DATA_REDIS_KEY = "data_";

    /** 
     * redis过期时间,以秒为单位 
     */  
    public final static int EXRP_HOUR = 60 * 60;            //一小时  
    public final static int EXRP_HALF_DAY = 60 * 60 * 12;        //半天  
    public final static int EXRP_DAY = 60 * 60 * 24;        //一天  
    public final static int EXRP_MONTH = 60 * 60 * 24 * 30; //一个月 

    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis连接池
     */
    public static void initialPool(String path){
        Properties prop = new Properties(); 
        try {
            prop.load(JedisPoolCacheUtils.class.getClassLoader().getResourceAsStream(path+"-conf/redis.properties"));
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(Detect.asPrimitiveInt(prop.getProperty("redis.pool.maxActive")));
            config.setMaxIdle(Detect.asPrimitiveInt(prop.getProperty("redis.pool.maxIdle")));
            config.setMinIdle(Detect.asPrimitiveInt(prop.getProperty("redis.pool.minIdle")));
            config.setMaxWaitMillis(Detect.asPrimitiveInt(prop.getProperty("redis.pool.maxWait")));
            config.setTestOnBorrow(true);
            config.setTestOnReturn(true);
            config.setTestWhileIdle(true);
            String host = prop.getProperty("redis.host");
            String port = prop.getProperty("redis.port");
            String timeOut = prop.getProperty("redis.timeout");
            jedisPool = new JedisPool(config, host, Detect.asPrimitiveInt(port), Detect.asPrimitiveInt(timeOut));
        } catch (Exception e) {
            log.error("First create JedisPool error : "+e);
            try{
                //如果第一个IP异常,则访问第二个IP
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxTotal(Detect.asPrimitiveInt(PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.pool.maxActive")));
                config.setMaxIdle(Detect.asPrimitiveInt(PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.pool.maxIdle")));
                config.setMinIdle(Detect.asPrimitiveInt(PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.pool.minIdle")));
                config.setMaxWaitMillis(Detect.asPrimitiveInt(PropertiesUtil.getValueByBundleFromConf(path+"-redis.properties","redis.pool.maxWait")));
                config.setTestOnBorrow(true);
                String host = PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.host");
                String port = PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.port");
                String timeOut = PropertiesUtil.getValueByBundleFromConf(path+"-conf/redis.properties","redis.timeout");
                jedisPool = new JedisPool(config, host, Detect.asPrimitiveInt(port), Detect.asPrimitiveInt(timeOut));
            }catch(Exception e2){
                log.error("Second create JedisPool error : "+e2);
            }
        }
        //Jedis jedis = jedisPool.getResource();
        //log.info("=====初始化redis池成功!  状态:"+ jedis.ping());
        log.info("=====初始化redis池成功!");
    }


    /**
     * 
      * setVExpire(设置key值,同时设置失效时间 秒)
      * @Title: setVExpire
      * @param @param key
      * @param @param value
      * @param @param seconds
      * @param index 具体数据库 默认使用0号库
      * @return void
      * @throws
     */
    public static <V> void setVExpire(String key, V value,int seconds,int index) {
        String json = JsonUtil.object2json(value);
        //String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            jedis.set(DATA_REDIS_KEY +key, json);
            jedis.expire(DATA_REDIS_KEY +key, seconds);
        } catch (Exception e) {
            log.error("setV初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }

    }
    /**
     * 
      * (存入redis数据)
      * @Title: setV
      * @param @param key
      * @param @param value
      * @param index 具体数据库 
      * @return void
      * @throws
     */
    public static <V> void setV(String key, V value,int index) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            jedis.set(DATA_REDIS_KEY +key, json);
        } catch (Exception e) {
            log.error("setV初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }

    }

    /**
     * 
      * getV(获取redis数据信息)
      * @Title: getV
      * @param @param key
      * @param index 具体数据库 0:常用数据存储      3:session数据存储
      * @param @return
      * @return V
      * @throws
     */
    @SuppressWarnings("unchecked")
    public static <V> V getV(String key,int index) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            value = jedis.get(DATA_REDIS_KEY +key);
        } catch (Exception e) {
            log.error("getV初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
        return (V)JSONObject.parse(value);
    }
    /**
     * 
      * getVString(返回json字符串)
      * @Title: getVString
      * @param @param key
      * @param @param index
      * @param @return
      * @return String
      * @throws
     */
    public static String getVStr(String key,int index) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(index);
            value = jedis.get(DATA_REDIS_KEY +key);
        } catch (Exception e) {
            log.error("getVString初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
        return value;
    }

    /**
     * 
     * Push(存入 数据到队列中)
     * 
     * @Title: Push
     * @param @param key
     * @param @param value
     * @return void
     * @throws
     */
    public static <V> void Push(String key, V value) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            log.info("存入 数据到队列中");
            jedis = jedisPool.getResource();
            jedis.select(15);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
    }
    /**
     * 
     * Push(存入 数据到队列中)
     * 
     * @Title: PushV
     * @param  key
     * @param value
     * @param dBNum
     * @return void
     * @throws
     */
    public static <V> void PushV(String key, V value,int dBNum) {
        String json = JSON.toJSONString(value);
        Jedis jedis = null;
        try {
            log.info("存入 数据到队列中");
            jedis = jedisPool.getResource();
            jedis.select(dBNum);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 
     * Push(存入 数据到队列中)
     * 
     * @Title: Push
     * @param @param key
     * @param @param value
     * @return void
     * @throws
     */
    public static <V> void PushEmail(String key, V value) {

        String json = JsonUtil.object2json(value);
        Jedis jedis = null;
        try {
            log.info("存入 数据到队列中");
            jedis = jedisPool.getResource();
            jedis.select(15);
            jedis.lpush(key, json);
        } catch (Exception e) {
            log.error("Push初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
    }

    /**
     * 
     * Pop(从队列中取值)
     * 
     * @Title: Pop
     * @param @param key
     * @param @return
     * @return V
     * @throws
     */
    @SuppressWarnings("unchecked")
    public static <V> V Pop(String key) {
        String value = "";
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(15);
            value = jedis.rpop(DATA_REDIS_KEY +key);
        } catch (Exception e) {
            log.error("Pop初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }
        return (V) value;
    }


    /**
     * 
     * expireKey(限时存入redis服务器)
     * 
     * @Title: expireKey
     * @param @param key
     * @param @param seconds
     * @return void
     * @throws
     */
    public static void expireKey(String key, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.select(3);
            jedis.expire(DATA_REDIS_KEY +key, seconds);
        } catch (Exception e) {
            log.error("Pop初始化jedis异常:" + e);
            if (jedis != null) {
                //jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        } finally {
            closeJedis(jedis);
        }

    }

    /**
     * 
     * closeJedis(释放redis资源)
     * 
     * @Title: closeJedis
     * @param @param jedis
     * @return void
     * @throws
     */
    public static void closeJedis(Jedis jedis) {
        try {
            if (jedis != null) {
                /*jedisPool.returnBrokenResource(jedis);
                jedisPool.returnResource(jedis);
                jedisPool.returnResourceObject(jedis);*/
                //高版本jedis close 取代池回收
                jedis.close();
            }
        } catch (Exception e) {
            log.error("释放资源异常:" + e);
        }
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}

2.配置文件 redis.properties

#最大连接数
redis.pool.maxActive=300
#最大空闲连接数
redis.pool.maxIdle=150
#最小空闲连接数
redis.pool.minIdle=10
#最大等待时间
redis.pool.maxWait=300
#redis基本配置 ip 端口 超时
redis.host=10.200.9.251
redis.port=6379
redis.timeout=6000

3.配置文件 web.xml配置监听器 
配置监听器使项目启动自动初始化jedisPool

<listener>
    <listener-class>com.ithzk.common.listener.ApplicationListener</listener-class>
  </listener>

4.ApplicationListener监听器

package com.ithzk.common.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ithzk.common.Consts;
import com.ithzk.common.listener.load.LinkAdmin;
import com.ithzk.common.redis.JedisPoolCacheUtils;

public class ApplicationListener implements ServletContextListener {

    private static Logger log = LoggerFactory.getLogger(ApplicationListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        initProjectEnvironment();       
    }

    /**
     * 初始化项目环境
     */
    private void initProjectEnvironment() {
        //初始化jedis池
        JedisPoolCacheUtils.initialPool(path);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) { }

}

5.使用jedisPool操作数据

package com.ithzk.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ithzk.common.consts.Consts;
import com.ithzk.common.exception.NotMactionException;
import com.ithzk.common.redis.JedisPoolCacheUtils;
import com.ithzk.common.util.Base64Util;
import com.ithzk.common.util.CdnUtil;
import com.ithzk.common.util.Detect;
import com.ithzk.common.util.HttpObjUtil;
import com.ithzk.common.util.Inspection;
import com.ithzk.common.util.JsonUtil;
import com.ithzk.common.util.Response;
import com.ithzk.service.IDataService ;

@Controller
@RequestMapping("/data")
public class DataController {

    private static Logger log = LoggerFactory.getLogger(DataController .class);
    @Autowired
    private IDataService dataService;

    @RequestMapping(value="/mkDetails",method=RequestMethod.POST)
    public void mkDetails(HttpServletResponse hResponse,HttpServletRequest request) throws IOException {
        hResponse.setCharacterEncoding("UTF-8");
        hResponse.setContentType("text/html;charset=utf-8");
        //跨域请求  * 允许所有
        hResponse.setHeader("Access-Control-Allow-Origin", "*");
        hResponse.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
        hResponse.setHeader("Access-Control-Max-Age", "3600");
        hResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        PrintWriter out = hResponse.getWriter();
        Response response = new Response();
        response.setSuccess(true);
        String user= (String) request.getParameter("user");
        if (Detect.notEmpty(mac)) {
            String redisResponse = JedisPoolCacheUtils.getVStr(user.trim(), 0);
            //Response parseObject = JSON.parseObject(redisResponse,Response.class);
            if (Detect.notEmpty(redisResponse)) {
                log.info("=======>redis "+redisResponse);
                JsonUtil.writeDirect(out, redisResponse);
                //JsonUtil.write(out, parseObject);
            }else {
                response = dataService.mkDetails(user.trim());
                log.info("=======>mysql "+response.toString());
                JedisPoolCacheUtils.setVExpire(user.trim(), response, JedisPoolCacheUtils.EXRP_HALF_DAY, 0);
            }
        }else {
            response.setSuccess(false);
            response.setCode(4001);
            response.setMsg("参数无效!");
        }
        JsonUtil.write(out, response);
    }

}

/*jedisPool.returnBrokenResource(jedis); 
jedisPool.returnResource(jedis); 
jedisPool.returnResourceObject(jedis);*/ 
//高版本jedis close 取代池回收 
jedis.close();

6.回收资源

老版本
jedisPool.returnBrokenResource(jedis);
jedisPool.returnResource(jedis);
jedisPool.returnResourceObject(jedis);
高版本jedis close 取代池回收
jedis.close();

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197045.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • preference用法for_notification用法

    preference用法for_notification用法PreferenceFragment引入在Android3.0之前,设置界面使用PreferenceActivity,在Android3.0之后,官方推荐使用PreferenceFragment,对应于碎片化技术。使用新建Fragment继承PreferenceFragment,加载选项配置xml文件。publicstaticclassNotificationPreferenceFr…

    2022年9月7日
    0
  • mse均方误差例题_误差函数计算器

    mse均方误差例题_误差函数计算器文章目录背景函数代码调用方法调用测试函数背景本人最近需要写多个仿真,需要大量用到MSE(均方误差)计算,于是干脆将MSE运算封装为函数,后续使用直接进行调用即可。函数代码%Project:均方误差函数%Author:Jace%Data:2021/11/01%====================函数体====================function[MSE]=MSE(Dim,Step,N,xkf,x)%====================分配空间=======

    2022年9月30日
    0
  • vim编辑器,可以实现保存退出()_vim进入编辑模式如何保存并退出

    vim编辑器,可以实现保存退出()_vim进入编辑模式如何保存并退出目录1.Vim模式2.在Vim/Vi中打开文件3.在Vim/Vi中保存文件4.保存文件并退出Vim/Vi5.退出Vim/Vi而不保存文件1.Vim模式启动Vim编辑器时,您处于正常模式。在这种模式下,您可以使用vim命令并浏览文件。要输入文字,您需要按i键进入插入模式。使用此模式,您可以像在常规文本编辑器中一样插入和删除字符。要从其他任何模式返回正常模式,只需按Esc键。2.在Vim/Vi中打开文件要使用Vim打开文件,请键入vim,然后输入要编辑或创建的文件的.

    2022年8月24日
    3
  • java 调用bapi_BAPI的简单实现步骤

    java 调用bapi_BAPI的简单实现步骤一,创建FunctionModule1,在SE11,创建需要的structure(必须为flat类型,否则会出现ReferenceparametersarenotallowedwithRFC)2,在SE80,建Functiongroup3,在SE37,创建FunctionModule(import的参数入药是value传值)Note:一个FunctionGroup只能包含一个B…

    2022年7月24日
    2
  • java中的关键字有哪些_java关键字有哪些?java关键字大全

    java中的关键字有哪些_java关键字有哪些?java关键字大全你知道java关键词都有哪些吗?下面小编就对于java关键词做了一次集合的大整理,下面就来和小编一起来了解一下,java的关键词吧!一、什么是java关键字?关键字是电脑语言里事先定义的,有特别意义的标识符。程序员利用关键字来告诉编译器其声明的变量类型、类、方法特性等信息。二、java关键字大全1、abstract-表明类或者成员方法具有抽象属性2、assert-断言,用来进行程序调试3、bool…

    2022年7月7日
    22
  • MSM8937-MSM8953 I2C 配置调试指南

    MSM8937-MSM8953 I2C 配置调试指南 一、I2C配置(硬件描述)1.根据原理图,查找相关的i2c引脚对应的GPIO值,以GPIO10作为I2C_SDA,GPIO11作为I2C_SCL为例。查找GPIO10与GPIO11对应的BLSP,以及检查GPIO10与GPIO11是否可以作为I2C来使用。根据文档,GPIO10对应BLSP3_1,GPIO11对应BLSP3_0。GPIOFUNCTIONGPIO_6,GP1…

    2022年10月9日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号