【spring-boot - 整合Reids(单机版)】 1.引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--SpringBoot与Redis整合依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> 2.配置application.properties server.port=8080 server.servlet.encoding.charset=UTF-8 # 应用名称 spring.application.name=redis-sample spring.jackson.date-format='yyyy-MM-dd HH:mm:ss' spring.jackson.time-zone=GMT+8 # always:始终包含该属性,与该属性的值无关; non_null:属性字段值为空则不会返回该字段,即value为null则key不被返回 spring.jackson.default-property-inclusion=always spring.mvc.pathmatch.matching-strategy=ant_path_matcher # ===============================redis single node config================================= spring.redis.database=0 spring.redis.host=192.168.xxx.xxx spring.redis.port=6379 # 连接密码 spring.redis.password=****** # 连接池配置,这里使用的lettuce spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1ms spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 3.出于序列化考虑,编写配置类:RedisConfig,指定RedisTemplate对应的key-value序列化方式 import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; 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(LettuceConnectionFactory lettuceConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(lettuceConnectionFactory); //设置key序列化方式: string redisTemplate.setKeySerializer(new StringRedisSerializer()); //设置value的序列化方式json,使用 GenericJackson2JsonRedisSerializer 替换默认序列化 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } } 4.使用 @Autowired private RedisTemplate redisTemplate; // 写入 redisTemplate.opsForValue().set(key, value); // 获取 Object obj = redisTemplate.opsForValue().get(key);