Explain the method of using Redis cache object in Java program in detail

  • 2021-07-10 19:52:09
  • OfStack

During this time, someone asked how to cache List set data in Java in Redis. In fact, it is very simple. There are two commonly used ways:

1. Using serialization, the object is serialized into binary format. Redis provides relevant API methods to store binary, and then deserialize the data back and convert it into objects.

2. Using Json and java objects can be converted to each other to store and take values.

Facing these two methods, a tool class is specially written to realize the data access function.

1. The first page configures the JedisPool connection pool object in the Spring framework, which can create the connection Jedis object of Redis. Of course, the related Jar package of Redis must be imported.

The Jar package for Jedis is as follows:

commons-pool2-2.3.jar
jedis-2.9.0.jar

To use Json, you also need to import the Jar package of Json:

commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.3.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar

Configure the JedisPool connection pool object in the configuration file


<!-- Redis  Connection pool configuration  -->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool"
	destroy-method="close">		
	<constructor-arg name="host" value="127.0.0.1" />
	<constructor-arg name="port" value="6379" />
</bean>

2. Create a tool class RedisUtil of Redis, which implements the access operation of the two methods mentioned above


package com.sgxy.util;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
 
@Component
public class RedisUtil {
	@Autowired
	JedisPool pool; // Jedis Connection pool 
	
  //  Judge Redis Is there a key in 
	public boolean existsKey(String key) {
		Jedis jedis = pool.getResource();
		boolean bool;
		try {
			bool = jedis.exists(key);
		} finally {
			jedis.close();
		}
		return bool;
	}
 
	//  Object in the cache 2 Binary data, deserialized into List Collection object 
	@SuppressWarnings("unchecked")
	public <T> List<T> getObject(String key, Class<T> clazz) {
		Jedis jedis = pool.getResource();
		// 2 Binary system  IO  Input stream 
		ByteArrayInputStream is = null;
		ObjectInputStream ois = null;
		try {
			//  Fetch from the cache 2 Binary data 
			byte[] b = jedis.get(key.getBytes());
			is = new ByteArrayInputStream(b);
			ois = new ObjectInputStream(is);
			//  Put 2 Binary conversion to T Collection of the specified type 
			return (List<T>) ois.readObject();
 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
				ois.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			jedis.close();
		}
		return null;
	}
 
	//  Serialize an object 2 Binary format and guarantee to Redis In the cache 
	public void saveObject(Object object, String key) {
		Jedis jedis = pool.getResource();
		// 2 Binary system  IO  Output stream 
		ByteArrayOutputStream os = null;
		ObjectOutputStream oos = null;
		try {
			os = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(os);
			oos.writeObject(object); // 2 Binary data 
			byte[] b = os.toByteArray();
			//  Deposit 2 Binary data to Redis In the cache 
			jedis.set(key.getBytes(), b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				oos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			jedis.close();
		}
	}
 
	//  Put List Collection object is converted to json Format is saved to the specified key 
	public void saveJsonArray(Object object, String key) {
		Jedis jedis = pool.getResource();
		try {
			//  Format into Json String 
			JSONArray array = JSONArray.fromObject(object);
			jedis.set(key, array.toString()); //  Save in cache 
		} finally {
			jedis.close();
		}
	}
 
	//  Take out by key Json String and converted to  Class<T> This T The type specified 
	@SuppressWarnings({ "static-access", "unchecked" })
	public <T> List<T> getJsonArray(String key, Class<T> clazz) {
		Jedis jedis = pool.getResource();
		try {
			String str = jedis.get(key);
			JSONArray array = JSONArray.fromObject(str);
			//  Converts a string back to a collection object  clazz Is the specified type 
			return (List<T>) array.toCollection(array, clazz);
		} finally {
			jedis.close();
		}
	}
}

Operate this tool class elsewhere in the Java program to do data processing:


@Controller // Note that this class is a controller 
@RequestMapping("grade") // Object that accesses this controller URL
public class GradeController {
	@Autowired //  From IOC Container injection business layer objects 
	GradeService gradeService;
	@Autowired
	JedisPool pool;
	@Autowired
	RedisUtil redisUtil;
 
	@RequestMapping("list") // Registration URL
	public ModelAndView list() { 
		List<Grade> grades = null;
		if (redisUtil.existsKey("g")) {
			System.out.println(" From Redis  Fetch data from cache ..");
			// Call deserialization method to fetch cached data 
      grades = redisUtil.getObject("g",Grade.class);			
			
      // Call Json The method of format conversion takes cached data 
      //grades = redisUtil.getJsonArray("gradeList", Grade.class);				
		} else {
			System.out.println(" Take data from the database and store it in the cache ..");			
			// Call the underlying method to fetch data from the database 
      grades = gradeService.find();
 
      // Call the serialization method to cache the data to the Redis Medium 
			redisUtil.saveObject(grades, "g");
 
      // Call Json The formatting method caches the data to the Redis Medium 
			//redisUtil.saveJsonArray(grades, "gradeList");		 
		}	 
		return new ModelAndView("gradeList", "grades", grades);
	}
}

Writing this, I hope it will be helpful to everyone.


Related articles: