springboot整合redis操作泛型

时间:2024-04-06 19:57:05

1.引入redis依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

 

2.设置key和value的序列化方式(这步是为了让key和value不出现看不懂的字符)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;
    @Bean
    RedisTemplate<String,Object> redisTemplate() {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        /* 使用Json序列化,默认是JDK序列化 */
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}
 

3.编写redis操作工具类

import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {
    @Resource   //注意:如果省略第二步,则不能用@Autowired
    private RedisTemplate<String, Object> redisTemplate;//RedisTemplate支持泛型
    
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }
}

 

4.向redis里面写入list对象

springboot整合redis操作泛型

 

4.从redis里面取出list对象

List<LongitudeLatitudeDTO> lonLat = (List<LongitudeLatitudeDTO>) redisUtil.get("allLonLat");