SoFunction
Updated on 2025-04-21

Java  How to operate redis

Java to redis operations

Operating Redis in Spring Boot project, you can use Spring Data Redis. Spring Data Redis is a module provided by Spring to simplify Redis data access, which provides an easy-to-use programming model to interact with Redis.

1. Add dependencies

First, you need toAdd Spring Boot's Redis starter dependency to the file:

<dependencies>
    <!-- Spring Boot Redis Starter -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!-- Connection pool management -->
    <dependency>
        <groupId></groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
</dependencies>

2. Configure Redis

existorConnection information for configuring Redis:

# Example=localhost
=6379
=yourpassword  # If yoursRedisSet password

Or use YAML format:

# Examplespring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword  # If yoursRedisSet password

3. Use RedisTemplate to operate Redis

RedisTemplateIt is a template class in Spring Data Redis for manipulating Redis. It provides rich APIs to manipulate Redis.

import ;
import ;
import ;
import ;
import ;
@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate; // Used to manipulate data of type String    @Autowired
    private RedisTemplate<Object, Object> redisTemplate; // Used to operate Object type data, can store any type of data, and requires manual conversion of types and other operations.    public void setKeyValue(String key, String value) {
        ValueOperations<String, String> opsForValue = ();
        (key, value);
    }
    public String getKeyValue(String key) {
        return ().get(key);
    }
}

Add, delete, modify and check operations

import ;
import ;
import ;
import ;
@Service
public class RedisService {
   @Autowired
   private RedisTemplate<String, Object> redisTemplate;
   //Storage data   public void set(String key, Object value) {
       ().set(key, value);
   }
   //Storage data and set expiration time   public void setWithExpire(String key, Object value, long timeout, TimeUnit unit) {
       ().set(key, value, timeout, unit);
   }
   // Get data   public Object get(String key) {
       return ().get(key);
   }
   // Delete data   public void delete(String key) {
       (key);
   }
}

Create temporary data and automatically delete it. By setting the expiration time, you can create temporary data. Redis automatically deletes data when they expire.

import ;
import ;
import ;
import ;
@Service
public class RedisService {
   @Autowired
   private RedisTemplate<String, Object> redisTemplate;
   // Create temporary data and set expiration time   public void createTemporaryData(String key, Object value, long timeout, TimeUnit unit) {
       ().set(key, value, timeout, unit);
   }
}

For example

().set("exampleKey", "exampleValue", 10, );

In this example, "exampleKey" will be set to "exampleValue", and this key-value pair will expire after 10 seconds.

4. Use Jackson2JsonRedisSerializer (optional) to customize the serialization method (storage objects)

If you need to store Java objects instead of simple strings, you can useJackson2JsonRedisSerializerto serialize and deserialize objects.

import ;
import ;
import ;
import ;
import ;
import .Jackson2JsonRedisSerializer;
import ;
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        (redisConnectionFactory);
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>();
        ObjectMapper om = new ObjectMapper();
        (, );  // All fields are visible, including private fields, etc.  Adjust according to actual situation.        (om);  // Setting up serialization tool class。You can also customize the serialization tool class。For example:new CustomObjectMapper()。 Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs。For example:new CustomObjectMapper()。Select the appropriate serialization tool class according to your needs

This is the end of this article about Java's redis operation method. For more related Java redis operation content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!