在Spring Boot中使用Redis存储List数据,可以通过使用RedisTemplate来实现。下面是一个示例代码:

  1. 添加Redis依赖

pom.xml文件中添加以下Redis依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis连接

application.propertiesapplication.yml文件中配置Redis连接信息:

spring.redis.host=your_redis_host
spring.redis.port=your_redis_port
  1. 创建Redis配置类

创建一个配置类,用于配置RedisTemplate:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

}
  1. 存入List数据

在需要存储List数据的地方,注入RedisTemplate,并使用opsForList()方法来操作List数据:

@Autowired
private RedisTemplate<String, Object> redisTemplate;

public void saveListData(String key, List<Object> dataList) {
    redisTemplate.opsForList().rightPushAll(key, dataList.toArray());
}
  1. 取出List数据

同样,在需要取出List数据的地方,注入RedisTemplate,并使用opsForList()方法来获取List数据:

@Autowired
private RedisTemplate<String, Object> redisTemplate;

public List<Object> getListData(String key) {
    return redisTemplate.opsForList().range(key, 0, -1);
}

通过以上步骤,你就可以在Spring Boot中使用Redis存储和获取List数据了

springboot如何在redis里存入list又取出list

原文地址: http://www.cveoy.top/t/topic/iPf0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录