Home > Database > Redis > body text

How to use Redis in SpringBoot

WBOY
Release: 2023-06-02 14:43:21
forward
1969 people have browsed it

1. Dependencies

Maven dependencies are as follows. It should be noted that spring-boot-starter-data-redis uses lettuce as the driver of the redis client by default, but lettuce is actually less practical. We Jedis is commonly used as the client driver, so lettuce is excluded here and jedis is introduced:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
Copy after login

2. Dependencies

Dependent relationships in spring data redis:

How to use Redis in SpringBoot

What this dependency wants to express is that Spring operates Redis through RedisConnection, and RedisConnection encapsulates the native Jedis line. To obtain the RedisConnection interface object is generated through RedisConnectionFactory.

3. Configuration

Configuration file for configuration:

# Redis 连接配置
# 单机 Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接池配置
spring.redis.jedis.pool.max-idle=30
spring.redis.jedis.pool.max-total=50
spring.redis.jedis.pool.max-wait=2000ms
Copy after login

Code for configuration:

@Configuration
public class RedisConfig {
    private RedisConnectionFactory connectionFactory = null;
 
    @Bean
    public RedisConnectionFactory initRedisConnectionFactory(){
        if(connectionFactory!=null){
            return connectionFactory;
        }
        JedisPoolConfig poolConfig =new JedisPoolConfig();
        //最大空闲数
        poolConfig.setMaxIdle(30);
        //最大连接数
        poolConfig.setMaxTotal(50);
        //最大等待毫秒数
        poolConfig.setMaxWaitMillis(2000);
        //创建Jedis连接工厂
        JedisConnectionFactory connectionFactory=new JedisConnectionFactory(poolConfig);
        //获取单机的redis配置,如果是集群的话用集群配置类
        RedisStandaloneConfiguration rscfg=connectionFactory.getStandaloneConfiguration();
        connectionFactory.setHostName("127.0.0.1");
        connectionFactory.setPort(6379);
        return connectionFactory;
    }
}
Copy after login

4.RedisTemplate

Here to explain What's more, if we use RedisConnection directly to operate redis, we need to manually go to RedisConnectionFactory to get RedisConnection, and we need to manually close RedisConnection every time. Therefore, Spring Data Redis provides RedisTemplate to facilitate operation. It is encapsulated from jedis and blocks the steps of resource acquisition and release.

The core thing to pay attention to when using RedisTemplate is its serializer. RedisTemplate has multiple serializers. Different serializers use serialization in the process of writing key values ​​and reading out redis. The methods will be different, and the serialized results will also be different. For example, when processing characters, you need to use a string-specific serializer, and when processing objects, you need to use an object-specific serializer.

The current serializers are as follows:

How to use Redis in SpringBoot

StringRedisSerializer:

StringRedisSerializer is the default Key used by RedisTemplate and Value's serializer, which serializes a string into a byte array, using UTF-8 encoding. Since Key and Value in Redis are both strings, the default StringRedisSerializer serializer can meet the needs of most situations.

Jackson2JsonRedisSerializer:

Jackson2JsonRedisSerializer is a serializer based on Jackson's Redis Key and Value. It can serialize objects into JSON format strings and store them. into Redis. To use the Jackson2JsonRedisSerializer serializer, you need to add a Jackson dependency. You can convert objects into JSON-formatted strings, or you can convert JSON-formatted strings into objects.

JdkSerializationRedisSerializer:

JdkSerializationRedisSerializer is a serializer based on Java's own serialization method. It can serialize objects into byte arrays for storage. Although JdkSerializationRedisSerializer is simple and easy to use, its efficiency is relatively low, and the serialized byte array is relatively large, making it unsuitable for storing large amounts of data.

GenericJackson2JsonRedisSerializer:

GenericJackson2JsonRedisSerializer is a Jackson2JsonRedisSerializer that supports generics, which can serialize any type of object and serialize the object into a JSON format string. It requires specifying the target type both during serialization and deserialization.

OxmSerializer:

OxmSerializer is a serializer based on Spring's O/X mapping framework, which supports serializing objects into XML format strings. Although OxmSerializer has high flexibility, its serialization and deserialization performance is low and it is not suitable for storing large amounts of data.

In short, when choosing a serializer, you need to choose based on the actual situation, and choose the appropriate serializer based on the data type and performance requirements.

When using it, you can just set it in. When setting, it gives you a lot of effective granularity options, whether it is effective for all redis type data structures, or it is effective for a certain type of redis data structure type:

How to use Redis in SpringBoot

For example, I want to use a String serializer, which will take effect globally:

@Bean
public RedisTemplate<Object,Object> initRedisTemplate(){
  RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
  redisTemplate.setDefaultSerializer(new StringRedisSerializer());
  return redisTemplate;
}
Copy after login

5. Basic operations

The following is to use RedisTemplate to operate redis Code examples of basic data types:

It should be noted that when @Bean defines RedisTemplate, the generic type must be aligned with the generic type when used.

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class RedisService {
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    public void setString(String key, String value) {
        stringRedisTemplate.opsForValue().set(key, value);
    }
 
    public String getString(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
 
    public void setHash(String key, String hashKey, Object value) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.put(key, hashKey, value);
    }
 
    public Object getHash(String key, String hashKey) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.get(key, hashKey);
    }
 
    public void setList(String key, Object value) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        listOps.rightPush(key, value);
    }
 
    public Object getList(String key, long index) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        return listOps.index(key, index);
    }
 
    public void setSet(String key, Object value) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        setOps.add(key, value);
    }
 
    public Object getSet(String key) {
        SetOperations<String, Object> setOps = redisTemplate.opsForSet();
        return setOps.members(key);
    }
 
    public void setZSet(String key, Object value, double score) {
        ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
        zsetOps.add(key, value, score);
    }
 
    public Object getZSet(String key, long start, long end) {
        ZSetOperations<String, Object> zsetOps = redisTemplate.opsForZSet();
        return zsetOps.range(key, start, end);
    }
 
}
Copy after login

6. Transactions

The following is a code example using transactions:

@Autowired
private RedisTemplate<String, String> redisTemplate;
 
public void transactionalOperation() {
    // 开启 Redis 事务
    redisTemplate.multi();
 
    try {
        // 执行多个 Redis 命令
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");
 
        // 提交事务
        redisTemplate.exec();
    } catch (Exception e) {
        // 回滚事务
        redisTemplate.discard();
    }
}
Copy after login

The above is the detailed content of How to use Redis in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!