SoFunction
Updated on 2025-03-08

Detailed explanation of how to use Redis cache objects in Java programs

During this period, people have been asking how to cache List collection data in Java in Redis. It is actually very simple. There are two common methods:

1. Using serialization, the object is serialized into a binary format. Redis provides relevant API methods to store binary, deserialize it when fetching the data and convert it into an object.

2. Use the method of converting Json and Java objects to store and retrieve values.

In view of these two methods, a tool class was specially written to implement the data access function.

1. Home Page Configure the JedisPool connection pool object in the Spring framework. This object can create a Redis connection Jedis object. Of course, the relevant Jar packages of Redis must be imported.

Jedis's Jar package is as follows:

commons-pool2-2.
jedis-2.9.

To use Json, you also need to import Json's Jar package:

commons-beanutils-1.8.
commons-collections-3.
commons-lang-2.
commons-logging-1.1.
ezmorph-1.0.
json-lib-2.

Configure JedisPool connection pool object in configuration file

<!-- Redis Connection pool configuration -->
<bean  class=""
	destroy-method="close">		
	<constructor-arg name="host" value="127.0.0.1" />
	<constructor-arg name="port" value="6379" />
</bean>

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

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
@Component
public class RedisUtil {
	@Autowired
	JedisPool pool; // Jedis connection pool	
  // Determine whether there is a key in Redis	public boolean existsKey(String key) {
		Jedis jedis = ();
		boolean bool;
		try {
			bool = (key);
		} finally {
			();
		}
		return bool;
	}
 
	// Take the binary data in the cache and deserialize it into a List collection object	@SuppressWarnings("unchecked")
	public <T> List<T> getObject(String key, Class<T> clazz) {
		Jedis jedis = ();
		// Binary IO input stream		ByteArrayInputStream is = null;
		ObjectInputStream ois = null;
		try {
			// Get binary data from cache			byte[] b = (());
			is = new ByteArrayInputStream(b);
			ois = new ObjectInputStream(is);
			// Convert binary to a set of T-specified type			return (List<T>) ();
 
		} catch (Exception e) {
			();
		} finally {
			try {
				();
				();
			} catch (Exception e2) {
				();
			}
			();
		}
		return null;
	}
 
	// Serialize the object in binary format and ensure it to the Redis cache	public void saveObject(Object object, String key) {
		Jedis jedis = ();
		// Binary IO output stream		ByteArrayOutputStream os = null;
		ObjectOutputStream oos = null;
		try {
			os = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(os);
			(object); // Binary data			byte[] b = ();
			//Save binary data into Redis cache			((), b);
		} catch (Exception e) {
			();
		} finally {
			try {
				();
				();
			} catch (Exception e2) {
				();
			}
			();
		}
	}
 
	// Convert List collection object to json format and save it to the specified key	public void saveJsonArray(Object object, String key) {
		Jedis jedis = ();
		try {
			// Format into Json string			JSONArray array = (object);
			(key, ()); // Save to cache		} finally {
			();
		}
	}
 
	// Take out the Json string by key and convert it to the type specified by Class<T>	@SuppressWarnings({ "static-access", "unchecked" })
	public &lt;T&gt; List&lt;T&gt; getJsonArray(String key, Class&lt;T&gt; clazz) {
		Jedis jedis = ();
		try {
			String str = (key);
			JSONArray array = (str);
			// Convert string back to the collection object clazz is the specified type			return (List&lt;T&gt;) (array, clazz);
		} finally {
			();
		}
	}
}

Operate this tool class in other places in Java programs to process data:

@Controller //Annotation of this class as a controller@RequestMapping("grade") //Register the URL to access this controllerpublic class GradeController {
	@Autowired // Inject business layer object from IOC container	GradeService gradeService;
	@Autowired
	JedisPool pool;
	@Autowired
	RedisUtil redisUtil;
 
	@RequestMapping("list") //Register URL	public ModelAndView list() { 
		List&lt;Grade&gt; grades = null;
		if (("g")) {
			("Fetch data from Redis cache....");
			//Call the deserialization method to get the cached data      grades = ("g",);			
			
      //Call the method of Json format conversion to get cached data      //grades = ("gradeList", );				
		} else {
			("Fetch data from the database and store it in the cache...");			
			//Call the underlying method to get data from the database      grades = ();
 
      //Calculating the serialization method to cache the data into Redis			(grades, "g");
 
      //Calculating Json formatting method to cache data into Redis			//(grades, "gradeList");		 
		}	 
		return new ModelAndView("gradeList", "grades", grades);
	}
}

Having said that, I hope it will be helpful to everyone.

The above is a detailed explanation and integration of the method of using Redis cache objects in Java programs introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!