项目中需要用到缓存减少数据库压力,选择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异常,则访问第二个IPJedisPoolConfig 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);@Overridepublic void contextInitialized(ServletContextEvent sce) {initProjectEnvironment();       }/*** 初始化项目环境*/private void initProjectEnvironment() {//初始化jedis池JedisPoolCacheUtils.initialPool(path);}@Overridepublic 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);@Autowiredprivate 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();

JedisPool工具类及使用相关推荐

  1. JedisPool 工具类(DCL 思想)

    1.工具类代码 package com.yanghui;import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; ...

  2. Java开发中的工具类——基于JedisPool的Redis工具类

    目录 一.Maven依赖 二.Redis配置类 三.使用@Cacheable注解进行数据缓存 四.自定义Redis工具类及使用 4.1 序列化工具类 4.2 redis客户端工具类 4.3 redis ...

  3. Jedis连接池:JedisPool及连接池工具类搭建

    文章目录 Jedis连接池 连接池建立步骤 代码案例 JedisPoolUtils工具类 创建配置文件 编写工具类 编写测试代码 Jedis连接池 连接池建立步骤 JedisPool的配置参数大部分是 ...

  4. Redis工具类的封装

    Redis工具类的封装 <dependency><groupId>redis.clients</groupId><artifactId>jedis< ...

  5. Redis使用及工具类

    原地址:https://www.cnblogs.com/wyy123/p/6078593.html [学会安装redis] 从redis.io下载最新版redis-X.Y.Z.tar.gz后解压,然后 ...

  6. Jedis工具类(含分布式锁的调用和释放)

    个人把工具类分为两部分: 一.连接池部分 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.j ...

  7. 关于jedis2.4以上版本的连接池配置,及工具类

    jedis.propertise 注意以前版本的maxAcitve和maxWait有所改变,JVM根据系统环境变量ServerType中的值 取不同的配置,实现多环境(测试环境.生产环境)集成. re ...

  8. Jedis工具类使用及设置

    Jedis是Redis数据库的java工具类,类似于JDBC中的Connection,也是对数据库进行CRUD的通道(这样说是不是有点不严谨~~~) 附上几个Redis的通用命令: key* 查看所有 ...

  9. RedisUtil工具类

    原文地址:http://blog.csdn.net/liuxiao723846/article/details/50401406 1.使用了jedis客户端,对Redis进行了封装,包括: 1)使用了 ...

最新文章

  1. JetBrains大力推广Kotlin为哪般?
  2. 【PC工具】解放双手:分享京东双十一任务脚本,双十一京东全民养红包活动自动脚本分享...
  3. QT下 cannot find -IGL的解决办法
  4. Cortex-M3-建立堆栈
  5. CRM Fiori应用 Appointment的close date字段
  6. WORD样式保存为主题集?
  7. 5000起步没商量!vivo NEX 3S 5G手机正式发布:骁龙865+无界瀑布屏加持
  8. 测试环境搭建mysql数据库_软件测试环境的搭建系列:[2] MySQL数据库的安装
  9. android studio刷rom,Android Studio 之 ROM【1】, Entity,Dao,Database
  10. 直方图匹配法(规则化)
  11. Apache双机热备
  12. 软件质量模型的六大特性和27个子特性
  13. Mimikatz的攻击及防御
  14. android截屏保存目录,Android实现截屏,将截图文件保存到本地文件夹
  15. 通过wait,notify等实现线程通讯
  16. Python3: 超简单个性动态二维码制作
  17. java 反射基础_Java反射的基本使
  18. 交换机级联后网速在底层交换机变慢的问题
  19. 深入剖析Spring架构与设计原理(一)
  20. 女生转行做什么工作好?想要转行互联网可以选择哪些方向?

热门文章

  1. springBoot(maven)项目引入本地jar并打包
  2. cnblog,我来了。
  3. C#读写EXCEL源码提示“office检测到此文件存在一个问题。为帮助保护您的计算机,不能打开此文件。 ”的解决
  4. 【python自动化】02. pywin32库自动操作键鼠(保姆级代码注释)
  5. 从零开始带你玩转单片机----------【第一期】
  6. 在线帮助你修改图片背景的工具 - Clipping Magic
  7. python 绘制花瓣_怎么用python画花朵
  8. 读取指定目录下的excel表格
  9. 解决java.lang.IllegalStateException: The content of the adapter has changed but ListView...的问题
  10. Spring拦截器进行登录拦截