Simple use of redis in Java

Simple use of redis in Java

Author: Yangxu network

Environment dependency: redis needs to be downloaded and installed

1, Introducing jar package into pom.xml of the project

1, In the project pom.xml Introduce in jar package
<!-- redis -->
<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
   <version>2.7.2</version>
</dependency>
<dependency>  
      <groupId>org.springframework.data</groupId>  
    <artifactId>spring-data-redis</artifactId>  
    <version>1.3.4.RELEASE</version>  
</dependency> 

2, Write a tool class

package com.yx.cus.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * redis Tool class
 *@author HHR
 *@date 2017 August 28, 2007 7:54:17 PM
 */ 
public class JedisClient{

   private  static  final  Logger   logger = LoggerFactory.getLogger(JedisClient.class);

   private  static  JedisPool  jedisPool = null;

   private  static Jedis jedis = null;

   public  static Jedis jedis_object = null;
// @Value("${spring.redis.host}") 
// private static String host;
// @Value("${spring.redis.password}") 
// private static String password;
// @Value("${spring.redis.port}") 
// private static Integer port;
// private static String host = "47.106.10.57";
private static String host = "192.168.0.123";//redis configured ip address
// private static String password = "9drur!@34";
   private static Integer port = 6379;//Port number of redis configuration


   static{
      if(jedisPool == null){
         JedisPoolConfig  config = new JedisPoolConfig(); 
         //Set the maximum number of connections
         config.setMaxTotal(500);
         //Set the maximum number of idle
         config.setMaxIdle(20);
         //Set the minimum number of idle
         config.setMinIdle(8);
         //Set timeout
         config.setMaxWaitMillis(3000);
         //Connection scan on Idle
         //config.setTestWhileIdle(true);
         //Indicates the number of milliseconds to sleep between two scans of idle object monitor
         //config.setTimeBetweenEvictionRunsMillis(30000);
         //Represents the maximum number of objects per scan for idle object monitor
         //config.setNumTestsPerEvictionRun(10);
         //Indicates the minimum time for an object to stay in the idle state before it can be scanned and expelled by the idle object monitor; this item only makes sense when the time between evaluation runsmillis is greater than 0
         //config.setMinEvictableIdleTimeMillis(60000);
         //Initialize connection pool
         jedisPool = new JedisPool(config, host, port);
         jedis_object = new   Jedis( host, port);
      }
   }

   private  JedisClient() {

   }

   private static Jedis  getJedisInstance(){

      try { 
         if(null == jedis){
            jedis = jedisPool.getResource();
//          jedis.auth(password);
         }
      } catch (Exception e) {
         logger.error("instantiation jedis fail.........", e);
      }
      return jedis;
   }

   /**
    * Set string content to cache 
    *@author HHR
    *@date 2017 3:19:41 PM, August 29, 2008
    */
   public static boolean set(String key, String value) throws Exception {
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.set(key, value);
         return true;
      } catch (Exception e) {
         logger.error("redis set Method failed...key="+key+"  value="+value, e);
      } finally {
         jedisPool.close();
      }
      return false;
   }



   /**
    * Set string content to cache, set expiration time
    *@author HHR
    *@date 2017 3:19:41 PM, August 29, 2008
    */
   public static boolean set(String key, String value,Integer seconds) throws Exception {
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.set(key, value);
         jedis.expire(key, seconds);
         return true;
      } catch (Exception e) {
         logger.error("redis set Method failed...key="+key+"  value="+value, e);
      } finally {
         jedisPool.close();
      }
      return false;
   }

   /**
    * Get content according to key
    *@author HHR
    *@date 2017 3:19:47 PM, August 29, 2008
    */
   public static Object get(String key) {
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         Object value = jedis.get(key);
         return value;
      } catch (Exception e) {
         logger.error("redis get Method failed...key="+key);
      } finally {
         jedisPool.close();
      }
      return null;
   }

   /**
    * Delete the object in the cache according to the key
    *@author HHR
    *@date 2017 3:19:53 PM, August 29, 2008
    */
   public static boolean del(String key) {
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.del(key);
         return true;
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return false;
   }

   /**
    * Get object according to key
    *@author HHR
    *@date 2017 3:19:58 PM, August 29, 2008
    */
   public static <T> T get(String key, Class<T> clazz) {
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         String value = jedis.get(key);
         return JSON.parseObject(value, clazz);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return null;
   }

   /**
    *  Set key expiration
    *@author HHR
    *@date 2017 3:20:03 PM, August 29, 2008
    */
   public  static   boolean  expire(String key,int seconds){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.expire(key, seconds);
         return  true;
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return false;
   }

   /**
    * list push
    *@author HHR
    *@date 2017 3:20:10 PM, August 29, 2010
    */
   public  static  boolean  lpush(String key,String value){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.lpush(key, value);
         return  true;
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return false;
   }

   /**
    * list lpop
    *@author HHR
    *@date 2017 August 29, 2014 3:20:14 PM
    */
   public  static  String  lpop(String key){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         return  jedis.lpop(key);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return null;
   }

   /**
    * list rpush
    *@author HHR
    *@date 2017 3:20:20 PM, August 29, 2008
    */
   public  static  boolean  rpush(String key,String value){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.lpush(key, value);
         return  true;
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return false;
   }

   /**
    * list rpop
    *@author HHR
    *@date 2017 3:20:27 PM, August 29, 2008
    */
   public  static  String  rpop(String key){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         return  jedis.rpop(key);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         jedisPool.close();
      }
      return null;
   }

   /**
    * Hash adding
    *@author HHR
    *@date 2017 3:20:32 PM, August 29, 2008
    */
   public  static  boolean  hsetAddField(String key,String fieldName,String value){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         jedis.hset(key, fieldName, value);
         return true;
      } catch (Exception e) {
         e.printStackTrace();
      }finally {
         jedisPool.close();
      }
      return  false;
   }

   /**
    * Used to increment the integer value of a key by 1
    *@author HHR
    *@date 2017 3:21:23 PM, August 29, 2008
    */
   public static Long incr(String key){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         return jedis.incr(key);
      } catch (Exception e) {
         e.printStackTrace();
         return -100l;
      }finally {
         jedisPool.close();
      }
   }

   /**
    * Judge whether key exists
    *@author HHR
    *@date 2017 August 29, 2004 3:20:42 PM
    */
   public static Boolean exists(String key){
      Jedis jedis = null;
      try {
         jedis = getJedisInstance();
         return jedis.exists(key);
      } catch (Exception e) {
         e.printStackTrace();
         return false;
      }finally {
         jedisPool.close();
      }
   }

}

1. Please note that there are two sections of code in red font, one is the ip address and the other is the port number, which needs to be consistent with that in the redis configuration file.
2. Generally, the default IP address is 127.0.0.1, and the default port number is 6379.
3. It can be modified in redis.conf (some are redis.windows.conf) under the redis installation directory
For example: bind 127.0.0.1
port 6379
You can also configure mult ip le IPS with spaces separated
For example: bind 127.0.0.1 192.168.0.123
*

**Note: to start redis after modification, you must start the specified conf configuration file,
For example, enter redis-server.exe redis.windows.conf in the command-line window and switch to the redis installation directory. You cannot enter redis server &, because this is the default configuration*

3, Main methods
1. data storage:
Method 1: set (String key,String val) this method needs to input two parameters, key and value
Method 2: set(String key,String val,Integer seconds) this method has one more parameter "expiration time", in seconds
2. Access data:
Get the data by calling the get(String key) method of the tool class
3. Delete objects in cache:
Call del(String key) method to delete

Tags: Jedis Redis Spring xml

Posted on Wed, 08 Jan 2020 13:01:00 -0500 by NJordan72