avatar

SpringBoot整合redis

摘要:本文介绍了SpringBoot中如何整合redis以及如何操作redis

SpringBoot整合redis


启动redis

首先我们来到redis文件夹下打开cmd窗口,运行命令

1
redis-server.exe redis.windows.conf

然后再打开另一个cmd窗口,运行命令

1
redis-cli.exe -h 127.0.0.1 -p 6379

这样我们就打开redis了,那么我们先创建一个项目。

创建redis项目

添加redis和spring security依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

在application.properties中配置

1
2
3
4
spring.redis.host=127.0.0.1
spring.redis.database=0
spring.redis.port=6379
spring.redis.password=11215858

创建HelloController

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
package com.example.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author: WJZheng
* @date: 2020/3/24 19:36
* @description:
*/

@RestController
public class HelloController {
@Autowired
StringRedisTemplate stringRedisTemplate;

@GetMapping("/set")
public void set() {
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.set("name", "william");
}

@GetMapping("/get")
public String get() {
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
return operations.get("name");
}
}

这样我们就可以操作redis了,首先我们访问一下http://localhost:8080/set,我们进入登陆页面,使用spring security的默认用户名和密码登录,这样就在redis中插入数据了。然后我们来查看redis中的数据变化。

然后我们再访问一下http://localhost:8080/get,我们就可以在前端页面访问到数据了。

Author: WJZheng
Link: https://wellenzheng.github.io/2020/03/24/SpringBoot%E6%95%B4%E5%90%88redis/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment