Use Redis-jedis in spring boot

Source: Internet
Author: User
Tags redis


1. Adding a jar package depends on using MAVEN form





<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId> spring-boot-starter-redis</artifactid>
   <version>1.4.7.RELEASE</version>
</ Dependency>
2. Project configuration file setting Redis information







 
redis:
 host: 
 port: 
 password: 
 pool:
  max-active: 8
  min-idle: 0
  max-idle: 8
  max-wait: 10000
 timeout: 0
database: 9
Note: Be sure to go under the spring node





3. New initialization Jedispool Bean let spring boot boot to load the bean's configuration information





@Configuration
@EnableCaching Public
class Jedisconfiguration {
    @Value ("${spring.redis.host}")
    Private String host;

    @Value ("${spring.redis.port}")
    private int port;

    @Value ("${spring.redis.timeout}")
    private int timeout;

    @Value ("${spring.redis.pool.max-idle}")
    private int maxidle;

    @Value ("${spring.redis.pool.max-wait}")
    private long maxwaitmillis;

    @Value ("${spring.redis.password}")
    private String password;
    @Bean public
    Jedispool redispoolfactory () {
        Jedispoolconfig jedispoolconfig = new Jedispoolconfig ();
        Jedispoolconfig.setmaxidle (maxidle);
        Jedispoolconfig.setmaxwaitmillis (Maxwaitmillis);
        Jedispool Jedispool = new Jedispool (jedispoolconfig, host, port, timeout, password);
        return jedispool;
    }
}
4. New Jedisutil class



public class JedisUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    private static JedisPool jedisPool = null;

    private static volatile Jedis jedis = null;
    public JedisUtil () {}

    public static Jedis getJedis () {
        if (jedis == null) {
            synchronized (Jedis.class) {
                if (jedis == null) {
                    jedis = getJedisPool (). getResource ();
                }
            }
        }
        return jedis;
    }

    public static JedisPool getJedisPool () {
        if (jedisPool == null) {
            synchronized (JedisPool.class) {
                if (jedisPool == null) {
                    jedisPool = applicationContext.getBean (JedisPool.class);
                }
            }
        }
        return jedisPool;
    }

    @Override
    public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
        if (JedisUtil.applicationContext == null) {
            JedisUtil.applicationContext = applicationContext; // Initialize spring applicationContext
        }
    }

    / **
     * See if it exists by key
     * @param key
     * @return
     * /
    public static boolean hasKey (String key) {
        return getJedis (). exists (key);
    }

    / **
     * Set key-value form data
     * @param key
     * @param value
     * @return
     * /
    public static String set (String key, String value) {
        String result = getJedis (). Set (key, value);
        return result;
    }

    / **
     * Set an expiration time
     * @param key
     * @param value
     * @param timeOut unit seconds
     * @return
     * /
    public static String set (String key, String value, int timeOut) {
        return getJedis (). setex (key, timeOut, value);
    }

    / **
     * Get value based on key
     * @param key
     * @return
     * /
    public static String getByKey (String key) {
        return getJedis (). get (key);
    }

    / **
     * Get all matching keys based on wildcards
     * @param pattern
     * @return
     * /
    public static Set <String> getKesByPattern (String pattern) {
        return getJedis (). keys (pattern);
    }

    / **
     * Delete by key
     * @param key
     * /
    public static void delByKey (String key) {
        getJedis (). del (key);
    }

    / **
     * Get the expiration time based on the key
     * @param key
     * @return
     * /
    public static long getTimeOutByKey (String key) {
        return getJedis (). ttl (key);
    }

    / **
     * Clear data [Use with caution. 】
     * /
    public static void flushDB () {
        getJedis (). flushDB ();
    }

    / **
     * Refresh expiration time
     * @param key
     * @param timeOut
     * @return
     * /
    public static long refreshLiveTime (String key, int timeOut) {
        return getJedis (). expire (key, timeOut);
    }
}






Note that there is no use of annotations to inject this class into spring instead of using the form of a tool class here implements Applicationcontextaware interface is required and then the Setapplicationcontext method is overridden to initialize the ApplicationContext, when using a bean instead of annotation injections such as @autowired, it is necessary to manually use Getbean to get the desired bean object, and finally to add the spring boot class
@Import ({ymlconfigutil.class, jedisutil.class})




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.