Spring Boot3.4.1 集成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>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.31</version>
</dependency>
第二步 引入配置
spring:redis:host: 127.0.0.1port: 6379password: ''timeout: 10slettuce:pool:min-idle: 0max-idle: 8max-active: 8max-wait: -1ms
第三步 编写redis配置类
@Configuration
@EnableCaching
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);template.setValueSerializer(new StringRedisSerializer());template.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(new StringRedisSerializer());template.afterPropertiesSet();return template;}
}
第四步 编写操作工具类
@Component
public class RedisUtils
{@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public final static long DEFAULT_EXPIRE = 60 * 60 * 24;public void set(String key, Object value){set(key, value, DEFAULT_EXPIRE);}public void set(String key, Object value, long expire){redisTemplate.opsForValue().set(key, toJson(value));redisTemplate.expire(key, expire, TimeUnit.SECONDS);}public String get(String key){return redisTemplate.opsForValue().get(key).toString();}public <T> T get(String key, Class<T> clazz){String value = redisTemplate.opsForValue().get(key).toString();return value == null ? null : fromJson(value, clazz);}public void delete(String key){redisTemplate.delete(key);}private String toJson(Object object){if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double|| object instanceof Boolean || object instanceof String){return String.valueOf(object);}return JSON.toJSONString(object);}private <T> T fromJson(String json, Class<T> clazz){return JSON.parseObject(json, clazz);}
}
第五步 测试
@RestController
@RequestMapping("test")
public class TestController {@Autowiredprivate RedisUtils redisUtils;@RequestMapping("/hello")public String hello() {redisUtils.set("test1","hello world");System.out.println(redisUtils.get("test1"));return "hello";}
}