一、前期准备
在搭建此QuickSatrt项目时,采用JDK1.8 + Springboot 2.0.5.RELEASE也许是非常有用的,保持一致的开发环境可以有效避免一些可能遇到的未知问题。此外,在跟随本文章搭建之前,请确保你已经会使用Spring boot、Maven构建项目,以及能够在Linux或Windows系统上正确的安装并启动Redis。
二、pom引入
引入关键jar:
org.springframework.boot
spring-boot-starter-data-redis
org.apache.commons
commons-pool2
二、配置
yaml文件配置:
server:
port: 9000
spring:
application:
name: TL-REDIS
http:
encoding:
charset: UTF-8
enabled: true
force: true
cache:
type: REDIS #枚举值:GENERIC,JCACHE,EHCACHE,HAZELCAST,INFINISPAN,COUCHBASE,REDIS,CAFFEINE,SIMPLE,NONE
redis:
use-key-prefix: true #是否使用key前缀
key-prefix: dev #key前缀
time-to-live: 20000 #缓存超时(单位:ms)
cache-null-values: true #是否缓存空值
redis:
host: 127.0.0.1
port: 6379
password: root
database: 0
timeout: 60s # 数据库连接超时时间,Spring boot2.0 中该参数的类型为Duration,在配置的时候需要指明单位
lettuce: # 连接池配置,Spring boot2.0中直接使用jedis或者lettuce配置连接池
pool:
# 最大空闲连接数
max-idle: 8
# 最小空闲连接数
min-idle: 1
# 等待可用连接的最大时间,负数为不限制
max-wait: -1s
# 最大活跃连接数,负数为不限制
max-active: -1
三、测试
在spring-data-redis包下,Spring提供了RedisTemplate类来进行对Redis的各种操作,它支持所有的Redis原生的api。RedisTemplate类继承于RedisAccessor类,并且实现了RedisOperations,和BeanClassLoaderAware结构。具体使用方式,在我们今后的文章中会有专门介绍。
本次测试代码如下:
importorg.junit.Test;importorg.junit.runner.RunWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.test.context.junit4.SpringRunner;importjava.util.concurrent.TimeUnit;
@SuppressWarnings("unchecked")
@RunWith(SpringRunner.class)
@SpringBootTest(classes= TlRedisApplication.class)public classTlRedisApplicationTests {
@AutowiredprivateRedisTemplate redisTemplate;/*** redis快速启动测试
* 目的 - 在键:test-key下,存储值:test-data,过期时间60秒*/@Testpublic voidredisQuickStartTest() {
redisTemplate.opsForValue().set("test-key", "test-data", 60, TimeUnit.SECONDS);
}
}
四、测试结果
使用管理工具Redis Desktop Manager连接到你的Redis,看到如下截图并在你设定的超时时间之后数据消失,则表示项目搭建成功。
五、测试结果分析
结果中在key和value中都出现了看似乱码的字符,产生这种情况的原因在于:spring-data-redis的RedisTemplate模板类在操作redis时默认使用JdkSerializationRedisSerializer来对key,value进行序列化操作。解决方案,请查看下一章节:Java Web技术之Redis(04) - 序列化与反序列化。