Springboot using Redis

Source: Internet
Author: User
Tags delete cache

I. Configuration of POM
    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-data-redis</artifactId>    </dependency>    <dependency>        <groupId>redis.clients</groupId>        <artifactId>jedis</artifactId>        <version>2.9.0</version>    </dependency>
Ii. creation of redis.properties under the resources
        redis.hostName=127.0.0.1        #端口号          redis.port=6379        #如果有密码          #redis.password=        #客户端超时时间单位是毫秒 默认是2000         redis.timeout=10000                  #最大空闲数          redis.maxIdle=300          #连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal          #redis.maxActive=600          #控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性          redis.maxTotal=1000          #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。          redis.maxWaitMillis=1000          #连接的最小空闲时间 默认1800000毫秒(30分钟)          redis.minEvictableIdleTimeMillis=300000          #每次释放连接的最大数目,默认3          redis.numTestsPerEvictionRun=1024          #逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1          redis.timeBetweenEvictionRunsMillis=30000          #是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个          redis.testOnBorrow=true          #在空闲时检查有效性, 默认false          redis.testWhileIdle=true          
Iii. Preparation of Redisconfig.java
    Package com.example.demo.config;    Import Com.example.demo.util.RedisUtil;    Import Org.slf4j.Logger;    Import Org.slf4j.LoggerFactory;    Import Org.springframework.beans.factory.annotation.Value;    Import Org.springframework.context.annotation.Bean;    Import org.springframework.context.annotation.Configuration;    Import Org.springframework.context.annotation.PropertySource;    Import Org.springframework.data.redis.connection.RedisConnectionFactory;    Import Org.springframework.data.redis.connection.jedis.JedisConnectionFactory;    Import Org.springframework.data.redis.core.RedisTemplate;    Import Org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;    Import Org.springframework.data.redis.serializer.StringRedisSerializer;    Import Redis.clients.jedis.JedisPoolConfig; /** * @author 12084 * @create 2018-08-13 9:58 */@Configuration @PropertySource ("Classpath:redis.propert IES ") public class Redisconfig {public static FINAL Logger Logger = Loggerfactory.getlogger (Redisconfig.class);    @Value ("${redis.hostname}") Private String hostName;    @Value ("${redis.port}") private Integer port;    @Value ("${redis.maxidle}") Private Integer maxidle;    @Value ("${redis.maxtotal}") Private Integer maxtotal;    @Value ("${redis.timeout}") Private Integer timeout;    @Value ("${redis.maxwaitmillis}") Private Integer Maxwaitmillis;    @Value ("${redis.minevictableidletimemillis}") Private Integer Minevictableidletimemillis;    @Value ("${redis.numtestsperevictionrun}") Private Integer Numtestsperevictionrun;    @Value ("${redis.timebetweenevictionrunsmillis}") Private long timebetweenevictionrunsmillis;    @Value ("${redis.testonborrow}") Private Boolean testonborrow;    @Value ("${redis.testwhileidle}") Private Boolean testwhileidle; /** * jedispoolconfig Connection Pool * * @return */@Bean public jedispoolconfig jedispoolconfig () {Jed Ispoolconfig jedispoolconfig = newJedispoolconfig ();        Maximum idle number jedispoolconfig.setmaxidle (Maxidle);        Maximum number of database connections for the connection pool jedispoolconfig.setmaxtotal (maxtotal);        Maximum build connection wait time Jedispoolconfig.setmaxwaitmillis (Maxwaitmillis);        Minimum idle time for eviction connections default 1800000 milliseconds (30 minutes) Jedispoolconfig.setminevictableidletimemillis (Minevictableidletimemillis);        Maximum number of evictions per eviction check if negative: 1/abs (n), default 3 Jedispoolconfig.setnumtestsperevictionrun (Numtestsperevictionrun); Eviction scan interval (milliseconds) if negative, the eviction thread is not run, Default-1 Jedispoolconfig.settimebetweenevictionrunsmillis (TIMEBETWEENEVICTIONRUNSM        Illis);        Whether to verify before removing the connection from the pool, and if the test fails, remove the connection from the pool and try to remove the other jedispoolconfig.settestonborrow (Testonborrow);        Check validity at idle time, default false Jedispoolconfig.settestwhileidle (Testwhileidle);    return jedispoolconfig; } @Bean Public jedisconnectionfactory jedisconnectionfactory (Jedispoolconfig jedispoolconfig) {jedisconnecti Onfactory jedisconnectionfactory = new JedisconnectIonfactory (Jedispoolconfig);        Connection Pool Jedisconnectionfactory.setpoolconfig (jedispoolconfig);        IP address jedisconnectionfactory.sethostname (hostName);        Port number Jedisconnectionfactory.setport (port);        If Redis is set with a password//jedisconnectionfactory.setpassword (password);        The client time-out unit is a millisecond jedisconnectionfactory.settimeout (timeout);    return jedisconnectionfactory; /** * Instantiate redistemplate Object * * @return */@Bean public redistemplate<string, object> func Tiondomainredistemplate (Redisconnectionfactory redisconnectionfactory) {redistemplate<string, Object> RedisT        Emplate = new redistemplate<> ();        Initdomainredistemplate (Redistemplate, redisconnectionfactory);    return redistemplate; }/** * Set data into Redis serialization mode and open transaction * * @param redistemplate * @param factory */private void Init Domainredistemplate (redistemplate<string, object> redistemplate, REdisconnectionfactory Factory) {//If you do not configure serializer, then the default is to use a String when stored, if the user type is stored, it will prompt the error user can ' t cast to string!        Redistemplate.setkeyserializer (New Stringredisserializer ());        Redistemplate.sethashkeyserializer (New Stringredisserializer ());        Redistemplate.sethashvalueserializer (New Genericjackson2jsonredisserializer ());        Redistemplate.setvalueserializer (New Genericjackson2jsonredisserializer ());        Turn on Transaction redistemplate.setenabletransactionsupport (TRUE);    Redistemplate.setconnectionfactory (Factory); }/** * Injection Package redistemplate * * @return redisutil * @throws * @Title: Redisutil */@Bean (name = "Redisutil") public redisutil redisutil (redistemplate<string, object> redistemplate) {redisutil redisUt        Il = new Redisutil ();        Redisutil.setredistemplate (redistemplate);    return redisutil; }    }
Iv. Writing Redisutil Tool classes
    Package com.example.demo.util;    Import Org.slf4j.Logger;    Import Org.slf4j.LoggerFactory;    Import Org.springframework.data.redis.core.RedisTemplate;        Import Org.springframework.util.CollectionUtils;    Import java.util.List;    Import Java.util.Map;    Import Java.util.Set;        Import Java.util.concurrent.TimeUnit; /** * @author 12084 * @create 2018-08-13 10:31 */public class Redisutil {public static final Logger Lo    Gger = Loggerfactory.getlogger (Redisutil.class);    Private redistemplate<string, object> redistemplate; public void Setredistemplate (redistemplate<string, object> redistemplate) {this.redistemplate = RedisTemplat    E }/** * Specify cache Expiration Time * @param key * @param time (seconds) * @return */public boolean expire (String ke Y, long time) {try{if (Time > 0) {redistemplate.expire (key, Time, Timeunit.seconds)            ;        } return true; }catch (Exception e) {logger.error ("Redisutil.expire error:", e);        return false; }}/** * Gets expiration time based on key * * @param key key cannot be null * @return time (seconds) returned 0 is permanent valid */public long get    Expire (String key) {return Redistemplate.getexpire (key, timeunit.seconds);        }/** * Determines if key exists * @param key key * @return True exists false does not exist */public Boolean haskey (String key) {        try{return Redistemplate.haskey (key);            }catch (Exception e) {logger.error ("Redisutil.haskey error:", e);        return false; }}/** * Delete cache * @param key can pass a value or multiple */public void del (String ... key) {if (key = null &amp            ;& key.length > 0) {if (key.length = = 1) {redistemplate.delete (key[0]);            }else {redistemplate.delete (collectionutils.arraytolist (key)); }}}/** * Normal cache gets * * @param key key * @retUrn Value */public Object get (String key) {return key = = null? Null:redisTemplate.opsForValue (). get (key); }/** * Normal cache put * @param key * @param value * @return True Success false failed */public Boolean set (            String key,object value) {try {redistemplate.opsforvalue (). Set (key, value);        return true;            } catch (Exception e) {e.printstacktrace ();        return false; }}/** * Normal cache put and set time * @param key * @param value value * @param time (seconds) to be greater than 0 if duration is less than or equal to 0 will set unlimited Period * @return True Success false failed */public Boolean set (String key,object value,long time) {try {i            F (time>0) {Redistemplate.opsforvalue (). Set (key, value, time, timeunit.seconds);            }else{set (key, value);        } return true;            } catch (Exception e) {e.printstacktrace ();        return false; }    }    }
Five, write test class
  Package com.example.demo.service;    Import Com.example.demo.util.RedisUtil;    Import Org.junit.Test;    Import Org.junit.runner.RunWith;    Import Org.slf4j.Logger;    Import Org.slf4j.LoggerFactory;    Import org.springframework.beans.factory.annotation.Autowired;    Import Org.springframework.boot.test.context.SpringBootTest;    Import Org.springframework.test.context.junit4.SpringRunner; /** * @author 12084 * @create 2018-08-10 10:31 */@RunWith (springrunner.class) @SpringBootTest PU Blic class Redisservicetest {public static final Logger Logger = Loggerfactory.getlogger (redisservicetest.clas            s);                @Autowired private Redisutil Redisutil;    @Test public void T1 () {//Boolean LMJ = Redisutil.set ("LMJ", "520");                Logger.warn ("lmj:{}", LMJ);            String lmj = (string) redisutil.get ("LMJ");        Logger.warn ("lmj:{}", LMJ); }        }

Springboot using Redis

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.