自定义 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 {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);// 设置键的序列化方式为 Stringtemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());// 设置值的序列化方式为 JSONtemplate.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 {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;// 存储数据到 Redispublic 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);}
}