在SpringBoot中使用Redis

 

Redis

使用docker

本地创建redis.conf

#daemonize yes
dir /data
logfile /data/redis.log
protected-mode no
#注释掉,可以远程访问
#bind 127.0.0.1
#开启AOF
appendonly yes
requirepass "password"
notify-keyspace-events Ex

启动redis容器docker run -v /root/redis/redis.conf:/usr/local/etc/redis/redis.conf -p 6379:6379 -d --name redis redis redis-server /usr/local/etc/redis/redis.conf

SpringBoot-Redis

使用

创建String到Object的redisTemplate

@Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        // 设置value的序列化规则和key的序列化规则
        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        template.setDefaultSerializer(fastJsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

自定义FastJsonSerializer

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

    private ObjectMapper objectMapper = new ObjectMapper();

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    FastJsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);

    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz);

    }

    public void setObjectMapper(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }

}

RedisUtil

@Component
public class RedisUtil {
    private static RedisTemplate<String, Object> redisTemplate;

    public RedisUtil(RedisTemplate<String, Object> autowiredRedisTemplate) {
        redisTemplate = autowiredRedisTemplate;
    }
    
    public static Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }


    public static void put(String key, Object value, int ttlSeconds) {
        redisTemplate.opsForValue().set(key, value, ttlSeconds, TimeUnit.SECONDS);
    }

    public static void expire(String key, long time) {
        if (time > 0) {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    public static void remove(String key){
        redisTemplate.delete(key);
    }
}

事件监听

注册监听

@Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
//        container.addMessageListener(new ServiceTokenExpiredListener(container), new PatternTopic("__keyevent@1__:expired"));
        return container;
    }

过期事件

@Service
public class DisposableNoticeServiceImpl extends KeyExpirationEventMessageListener implements DisposableNoticeService {
    public DisposableNoticeServiceImpl(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String redisKey = new String(message.getBody());
        log.info("expired key >>> " + redisKey);
        super.onMessage(message, pattern);
    }
}