使用java语言,自定义redistemplate

发布于:2025-02-10 ⋅ 阅读:(32) ⋅ 点赞:(0)
 自定义 RedisTemplate

为了方便使用,你可以创建一个自定义的 RedisTemplate,并将其注入到服务中。

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置键的序列化方式为 String
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置值的序列化方式为 JSON
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;
    }
}
在服务中使用 RedisTemplate

你可以在服务类中注入 RedisTemplate,并使用它来进行 Redis 操作。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class CacheService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储数据到 Redis
    public void setCacheData(String key, Object value, long expireTime) {
        redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS);
    }

    // 从 Redis 获取数据
    public Object getCacheData(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除 Redis 中的数据
    public void deleteCacheData(String key) {
        redisTemplate.delete(key);
    }

    // 检查 Redis 中是否存在某个键
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到