The configuration of Redis in Java projects is a good tool method

Source: Internet
Author: User
Tags redis server

Configuration file configuration for Redis:

#REDIS_CONFIGredis. Sentinels = X.x.x.x:p,x.x.x.x:p,x.x.x.x:predis.sentinel.master = Redis-masterredis.password = Passwordredispool.maxtotal = 6000redispool.maxidle = 300redispool.maxwaitmillis = 10000redispool.timeout = 100# Redis Standalone configuration redis.pool.host=127.0.0.1redis.pool.port=6379# The maximum number of objects that can hold the Idel state redis.pool.maxidle=100# The maximum number of objects allocated redis.pool.maxtotal=6000# the maximum time to wait for an available connection, in milliseconds, and a default value of-1, which means that it never times out. #如果超过等待时间, the jedisconnectionexceptionredis.pool.maxwaitmillis=10000redis.pool.timeout=20# is thrown directly How often do you check for idle connections in a connection pool redis.pool.timebetweenevictionrunsmillis=30000# How long the idle connection will be retracted redis.pool.minevictableidletimemillis=30000# when the borrow object method is called, the validity check is performed # when borrow (with) a Jedis instance, Whether the validate (validation) operation is performed in advance, and the resulting Jedis instances are available redis.pool.testonborrow=true####### #reids编码格式redis. encode=utf-8# # # # # #缓存过期时间 seconds 1000*60*60*24*7 seven days redis.expire=604800000### #是否开启Redis服务应用redis. unlock=false#redis.sentinel.host1= 127.0.0.1#redis.sentinel.port1=26379# #redis. sentinel.host2=127.0.0.1#redis.sentinel.port2=26479## Redis.pool.maxtotal=1024#redis.pool. maxidle=200#redis.pool.maxwaitmillis=1000#redis.pool.testonborrow=true## redis.pool.timebetweenevictionrunsmillis=30000#redis.pool.minevictableidletimemillis=30000# redis.pool.softminevictableidletimemillis=10000#redis.pool.numtestsperevictionrun=1024## #1000 *60*60*1# Redis.pool.expire=3600000#redis.pool.unlock=false

Implementation of the Redis tool class:

Package Com.base.redis;import Com.alibaba.fastjson.jsonarray;import Com.alibaba.fastjson.jsonobject;import Com.base.utils.calendarutil;import Com.base.utils.dateutils;import Com.google.common.collect.lists;import Com.google.common.collect.maps;import Com.petrochina.dao.basestockhlradiomapper;import Com.petrochina.pojo.baseprovincialarea;import Com.petrochina.pojo.basestockhlradio;import Org.apache.commons.lang.stringutils;import Org.apache.commons.pool2.impl.genericobjectpoolconfig;import Org.apache.log4j.logger;import Redis.clients.jedis.jedis;import Redis.clients.jedis.jedispool;import Redis.clients.jedis.jedispoolconfig;import Redis.clients.jedis.jedissentinelpool;import Javax.annotation.resource;import javax.swing.*;import java.util.*;/** * Explain:redis Connection pool */public final class                                    Redisutil {//========================================================================================////## Stand-alone configuration ##////========================================================================================////redis Server ip//Private    static string ADDR = "127.0.0.1";//private static string ADDR = Res.getstring ("Redis.pool.host");////redis port number//  private static Integer PORT = Integer.parseint (res.getstring ("Redis.pool.port"));///access password//private static String AUTH = ""; The maximum number of//////Available connection instances, the default is 8;////If the assignment is 1, it means no limit, if the pool has been assigned a maxactive Jedis instance, then the state of the pool is exhausted (exhausted)/PR Ivate static Integer max_total = Integer.parseint (res.getstring ("Redis.pool.maxTotal"));///////control how many states of a pool are idle ( Idle) Jedis instance, the default value is 8//private static Integer Max_idle = Integer.parseint (res.getstring ("Redis.pool.maxIdle"));///wait to The maximum time to use the connection, in milliseconds, and the default value is-1, which means that never times out. If the wait time is exceeded, the jedisconnectionexception//private static Integer Max_wait_millis = Integer.parseint is thrown directly (Res.getstrin G ("Redis.pool.maxWaitMillis"));//private static Integer TIMEOUT = Integer.parseint (Res.getstring (" Redis.pool.timeOut "));//   Whether the validate (validate) operation is performed in advance when a Jedis instance is borrow (with),///if True, the resulting Jedis instance is available//private static Boolean Test_on_borrow = Boolean.valueof (res.getstring ("Redis.pool.testOnBorrow"));//private static Jedispool Jedispool = null;private stat IC ResourceBundle res = resourcebundle.getbundle ("Redis");p rivate static Logger log = Logger.getlogger (Redisutil.class)    ;    private static String password;    private static Jedissentinelpool Jedispool;            static {try{string[] servers = res.getstring ("Redis.sentinels"). Split (",");            int maxtotal = Integer.parseint (res.getstring ("Redispool.maxtotal"));            int maxidle = Integer.parseint (res.getstring ("Redispool.maxidle"));            int maxwaitmillis = Integer.parseint (res.getstring ("Redispool.maxwaitmillis"));            int timeout = Integer.parseint (res.getstring ("redispool.timeout"));    Long Timebetweenevictionrunsmillis = long.valueof (res.getstring ("Redis.pool.timeBetweenEvictionRunsMillis"));        Long Minevictableidletimemillis = long.valueof (res.getstring ("Redis.pool.minEvictableIdleTimeMillis"));            String Sentinelmaster = res.getstring ("Redis.sentinel.master");            Password = res.getstring ("Redis.password");            Set<string> sentinels = new hashset<> (16);            for (String server:servers) {sentinels.add (server);            } genericobjectpoolconfig config = new Genericobjectpoolconfig ();            Config.setmaxtotal (maxtotal);            Config.setmaxidle (Maxidle);            Config.setmaxwaitmillis (Maxwaitmillis);            Config.settestonborrow (FALSE);            Config.settestonreturn (FALSE);            Config.settestwhileidle (TRUE);            Config.setminevictableidletimemillis (Minevictableidletimemillis);            Config.settimebetweenevictionrunsmillis (Timebetweenevictionrunsmillis); The Setinel client provides the master Autodiscover feature jedispool = new Jedissentinelpool (sentinelmaster,sentinels, Config,timeout,password);        }catch (Exception e) {e.printstacktrace (); }}/** * Get Jedis instance * @return */public static Jedis Getjedis () {Long seconds = system.current        Timemillis ();                try {if (Jedispool! = null) {Jedis Jedis = Jedispool.getresource ();            return Jedis;            }else{return null;            }} catch (Exception e) {e.printstacktrace ();        return null;        }} public static void Returnresource (final Jedis Jedis) {Long seconds = system.currenttimemillis ();        if (jedis!=null) {jedis.close ();        }} public static Jsonobject Verifykey (String key) {Jedis Jedis =null;        Jsonobject Jsonreturn = null;            try {Jedis = Getjedis ();            if (Jedis = = null) {return null;            } String JSON = Jedis.get (key); if (Json==null | | json.eqUals ("")) {Jsonreturn = null;            }else{Jsonreturn = Jsonobject.parseobject (JSON);        }} catch (Exception e) {e.printstacktrace ();            } finally {if (null! = Jedis) {returnresource (Jedis);    }} return Jsonreturn;        }/** * Verify that the alarm key exists * @param key * @return */public static string Verifywarnkey (String key) {        Jedis Jedis = null;        String datestr = null;            try {Jedis = Getjedis ();            Datestr = "";            if (Jedis! = null) {DATESTR = Jedis.get (key);        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis);    } return DATESTR;        public static map<string,string> Verifymap (String key) {map<string,string> reMap = null;        Jedis Jedis = null;       String Jsonreturn = null; try {Jedis = Getjedis ();            if (Jedis = = null) {return null;            } ReMap = Maps.newhashmap ();            ReMap = Jedis.hgetall (key);            if (Remap==null | | remap.size () = = 0) {reMap = null;        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis);    } return REMAP;        public static void SetData (string key, String jsonstring) {Jedis Jedis = null;        String Jsonreturn = null;            try {Jedis = Getjedis ();                if (Jedis! = null) {String result = Jedis.set (key, jsonstring);                            SYSTEM.OUT.PRINTLN (result);            Jedis.expireat (Key,calendarutil.getexpiretime ());        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis); }}//Put string data public static void SetstriNg (string key, String value) {Jedis Jedis = null;        String Jsonreturn = null;            try {Jedis = Getjedis ();            if (Jedis! = null) {Jedis.set (key,value);        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis);        }}//delete public static void DeleteKey (String key) {Jedis Jedis = null based on key;        String Jsonreturn = null;            try {Jedis = Getjedis ();            if (Jedis! = null) {Jedis.del (key);        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis);        }} public static void Setmapdata (String key, map<string,string> Map) {Jedis Jedis = null;        String Jsonreturn = null;            try {Jedis = Getjedis ();                            if (Jedis! = null) {Jedis.hmset (KEY,MAP); Jedis. Expireat (Key,calendarutil.getexpiretime ());        }} catch (Exception e) {e.printstacktrace ();        } finally {Returnresource (Jedis); }    }}

  

Good resources hope to support ha ~ ~

The configuration of Redis in Java projects is a good tool method

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.