开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 01 天,点击查看活动详情
The open source, in-memory data store used by millions of developers as a database, cache, streaming engine, and message broker.
Redis 是一个开源的、内存数据库,因其高性能及高吞吐量,而广泛应用于各类项目中。 在很多开源软件中,你也能发现它的身影。 今天,我们将来探究下如何在 Spring Boot 应用中整合 Redis。
01-快速开始
得益于众多 starter,我们可以快速地将 Redis 映入到现有的 Spring Boot 项目中。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
可通过 spring.redis.url 来指定要连接的 Redis 实例,其格式如下:
redis://$USER_NAME:$PASSWORD@$HOST:$PORT
其中:
- $USER_NAME 是要连接的用户,默认值为
default; - $PASSWORD 是密码,由 Redis 实例使用的 redis.conf 文件中的
requirepass ***指定; - $HOST 为 Redis 实例运行的主机 IP,默认为 localhost,即 127.0.0.1;
- $PORT 为 Redis 实例监听的端口,默认为 6379,由 redis.conf 中的
port xxx指定;
spring-boot-autoconfigure 中的 RedisProperties 会从环境变量中读取 spring.redis 开头的变量,例如 host / url / timeout 等等。
RedisAutoConfiguration 根据 classpath 中的类信息,自动配置使用 Lettuce(默认选项)或 Jedis 作为 Redis-cli 实现,与服务端交互。
并且,它会向应用上下文容器中,注入两个 Template 类的对象:
- RedisTemplate<Object, Object>,类型参数指定了 K-V 的类型;
- StringRedisTemplate extends RedisTemplate<String, String>,说明 K-V 都是 String 类型;
了解了上面的信息,我们在应用程序中就可以通过如下的方式与 Redis 进行交互:
public class RedisDemo {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void demo() {
redisTemplate.opsForValue().set("foo", "bar");
String foo = (String) redisTemplate.opsForValue().get("foo");
// 或者,如果 k-v 都是 String 类型的,可以使用
stringRedisTemplate.set("tar", "gar");
String tar = stringRedisTemplate.get("tar");
}
}
不难看出,通过 spring-boot-starter-data-redis 整合 Redis 到现有的 Spring Boot 进程是非常方便的。
02-Redis Client for Windows
在 Linux 系统中,我们可以通过源代码编译出 redis-server 和 redis-cli,后者用于连接到 Redis 实例上。 在 Windows 上,可以通过 microsoftarchive / redis 下载预先编译好的 redis-cli 应用程序。 下载完成后,解压到某个目录 REDIS_HOME 下,然后将 %REDIS_HOME% 添加到 path 环境变量中,然后在 cmd 中就能使用了。
redis-cli -h localhost -p 6379 -a redis123
除了这个终端界面外,还可以使用带 GUI 的 redis-cli 客户端 AnotherRedisDesktopManager。 如下是该工具的界面截图。
相比于终端,操作更便利一点。