前言
Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。
Redis安装
具体安装过程可参考Redis 安装 。
pom.xml文件
springboot2.0的redis整合包多出lettuce连接池,需要commons-pool2,所以项目pom依赖要添加commons-pool2。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| <dependencies> <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>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies>
|
配置文件
Lettuce 是一个可伸缩的线程安全的 Redis 客户端,支持同步、异步和响应式模式。多个线程可以共享一个连接实例,而不必担心多线程并发问题。它基于优秀 Netty NIO 框架构建,支持 Redis 的高级功能,如 Sentinel,集群,流水线,自动重新连接和 Redis 数据模型。SpringBoot 2.x已经使用Lettuce代替Jedis客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| spring: redis: database: 0 host: localhost port: 6379 password: timeout: 60ms lettuce: pool: max-active: 8 max-wait: -1ms max-idle: 8 min-idle: 0
|
Redis配置
SpringBoot默认提供了两个使用Redis的类StringRedisTemplate和RedisTemplate,其中RedisTemplate可以支持Redis没有的缓存对象的操作;而StringRedisTemplate用来存储字符串,其实是RedisTemplate<String, String>的实现类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport {
@Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(1)); RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).build(); return cacheManager; }
@Bean public RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
|
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class User implements Serializable { private String name; private int age; private List<String> education;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public List<String> getEducation() { return education; }
public void setEducation(List<String> education) { this.education = education; } }
|
controller类
- opsForValue:对应 String(字符串)
- opsForZSet:对应 ZSet(有序集合)
- opsForHash:对应 Hash(哈希)
- opsForList:对应 List(列表)
- opsForSet:对应 Set(集合)
- opsForGeo:对应 GEO(地理位置)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| @RestController public class RedisController {
@Autowired private RedisTemplate redisTemplate;
@RequestMapping("/set") public String HelloSpring(String key, String value) { redisTemplate.opsForValue().set(key, value); return String.format("redis set成功!key=%s,value=%s", key, value); }
@RequestMapping("/get") public String HelloSpring(String key) { String value = (String) redisTemplate.opsForValue().get(key); return "redis get结果 value=" + value; }
@RequestMapping("/setUser") public String setUser() { User user = new User(); user.setName("admin"); user.setAge(22); List<String> list = new ArrayList<>(); list.add("小学"); list.add("初中"); list.add("高中"); list.add("大学"); user.setEducation(list); redisTemplate.opsForValue().set("userInfo", user); return "success"; }
@RequestMapping("/getUser") public User getUser() { return (User) redisTemplate.opsForValue().get("userInfo"); } }
|
测试
启动Redis
打开一个 cmd 窗口 使用 cd 命令切换目录到 redis目录 运行:
1
| redis-server.exe redis.windows.conf
|
连接Redis
另启一个 cmd 窗口,原来的不要关闭,不然就无法访问服务端了。切换到 redis 目录下运行:
1
| redis-cli.exe -h 127.0.0.1 -p 6379
|

访问测试
访问http://localhost:8080/setUser ,通过get 命令可查看数据

通过命令清理Redis
可通过flushall 命令清理数据

RedisTemplate和StringRedisTemplate
1、StringRedisTemplate
- 主要用来存储字符串,StringRedisSerializer的泛型指定的是String。当存入对象时,会报错 :can not cast into String。
- 可见性强,更易维护。如果过都是字符串存储可考虑用StringRedisTemplate。
2、RedisTemplate
- 可以用来存储对象,但是要实现Serializable接口。
- 以二进制数组方式存储,内容没有可读性。(如图二所示)