本文共 3292 字,大约阅读时间需要 10 分钟。
在Spring Boot项目中,Redis依赖需要通过Maven仓库添加。以下是推荐的依赖配置:
org.springframework.boot spring-boot-starter-data-redis 2.0.0 redis.clients jedis io.lettuce lettuce-core redis.clients jedis 2.8.0 com.alibaba fastjson 1.2.47
注意:1.5版本的Spring Boot Redis依赖与2.0版本存在差异,特别是连接池技术的选择。这里使用jedis作为连接池,默认情况下会替换lettuce。
spring: redis: host: 172.30.66.104 port: 6379 password: 19e.com.cn database: 0 jedis: pool: max-active: 5 max-idle: 10 min-idle: 0
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration@AutoConfigureAfter(RedisAutoConfiguration.class)public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // JSON序列化 Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); // 字符串序列化 template.setKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.afterPropertiesSet(); return template; }} import com.qwe.common.demo.User;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.redis.core.RedisTemplate;@SpringBootTestpublic class RedisTest { @Autowired private RedisTemplate redisTemplate; @Test public void redisTest() { // 存储字符串 String key = "name"; redisTemplate.opsForValue().set(key, "qwe"); // 获取字符串 String value = (String) redisTemplate.opsForValue().get(key); System.out.println("key: " + key + ", value: " + value); // 存储对象 User user = new User("qw", 12); String userKey = "qwe"; redisTemplate.opsForValue().set(userKey, user); // 获取对象 User newUser = (User) redisTemplate.opsForValue().get(userKey); System.out.println("key: " + userKey + ", value: " + newUser); }} 以上配置和示例可根据实际项目需求进行调整,确保Redis服务器配置正确并且权限设置适当。
转载地址:http://jtqfk.baihongyu.com/