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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • SOA到底是什么

    SOA到底是什么SOA到底是什么 首先,SOA是一种开发思想。是一种松耦合的框架。可以让软件超越开发语言。SOA强调的是一种架构思想,组件化的灵活的开发方式。SOA是一场革命。一个应用程序的业务逻辑(businesslogic)或某些单独的功能被模块化并作为服务呈现给消费者或客户端。这些服务的关键是他们的松耦合特性。例如,服务的接口和实现相独立。应用开发人员或者系统集成者可以通过组合一个或多个服务来…

    2022年6月17日
    29
  • linux配置vscode python_vscode 配置 python

    linux配置vscode python_vscode 配置 python1.安装python2.安装vscode3.vscode安装所需插件1)、插件名称:python;这个是vscode提供的python官方插件,提供了python代码的调试,自动补全,代码格式化等功能。选择一个Python解释器选择一个Python解释器,在VSCode中,通过打开命令选项板(Ctrl+Shift+P)选择Python3解释器,开始键入…

    2025年6月10日
    3
  • Adaboost算法原理分析和实例+代码(简明易懂)

    Adaboost算法原理分析和实例+代码(简明易懂)Adaboost算法原理分析和实例+代码(简明易懂)【尊重原创,转载请注明出处】http://blog.csdn.net/guyuealian/article/details/70995333本人最初了解AdaBoost算法着实是花了几天时间,才明白他的基本原理。也许是自己能力有限吧,很多资料也是看得懵懵懂懂。网上找了一下关于Adaboost算法原理分析,大都是你复制我,我摘…

    2022年6月19日
    30
  • platform_driver_register 与 platform_device_register「建议收藏」

    platform_driver_register 与 platform_device_register「建议收藏」
    platfrom_driver_register()是在设备注册时进行绑定的.以USB为例:先插上USB设备并挂到总线上,然后在安装USB设备驱动的过程中,从总线上遍历各个设备,看是否有与驱动相匹配的设备,如果有,则两者绑定,就是platfrom_driver_register()
     
    platfrom_device_register()是在驱动注册时进行绑定的.以USB为例:先安装USB驱动程序,然后当USB设备插入时,就遍历总线上各个驱动,看两者是否匹配,如果相配则

    2022年7月14日
    21
  • rfq用户level2报价是几条(什么是建立在海量数据挖掘基础上)

    海量数据挖掘MiningMassiveDatasets(MMDs)-JureLeskovec courses学习笔记计算广告ComputationalAdvertising{博客内容:ComputationalAdvertising. Theproblemistoselectadstoshowwithotherinformation,typical

    2022年4月15日
    59
  • 集成环境哪个好?四大PHP集成开发环境比较

    集成环境哪个好?四大PHP集成开发环境比较http://www.5icool.org/a/201505/a11537.html专注了这么些年技术,没有养成记录和积累的习惯。如今乐于开源和分享经验,却停笔踌躇,不知该从何处说起。开通博客也有一段时间了,也没能写出一篇像样的文章,想了很久,觉得还是应该循序渐进,从搭建和配置开发、调试环境开始。主流的PHP集成开发环境(IntegratedDevelopmentEnvironment…

    2022年6月28日
    42

发表回复

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

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