1.引入依賴
在pom.xml中加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置文件
在application.yml中配置redis連接信息
# Redis數據庫索引(默認為0)
# Redis服務器地址
# Redis服務器連接端口
# 連接池最大連接數(使用負值表示沒有限制)
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
# 連接池中的最大空閑連接
# 連接池中的最小空閑連接
# 連接超時時間(毫秒)
spring:
redis:
database: 0
host: 192.168.88.200
port: 6379
jedis:
pool:
max-active: 20
max-wait: -1
max-idle: 10
min-idle: 0
timeout: 1000
3.使用
創建一個User實體類
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
@Data
@Accessors(chain = true)
public class User extends JdkSerializationRedisSerializer {
private Integer id;
private String name;
}
使用StringRedisTemplate(Key和Value都是String),完成對redis中String以及List數據結構的自定義User對象的存儲
import com.agan.entity.User;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@RestController
public class RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/user")
public Object addUser(@RequestBody User user){
stringRedisTemplate.opsForValue().set("user", JSON.toJSONString(user));
return "success";
}
@GetMapping("/user")
public User getUser(){
return JSON.parseObject(stringRedisTemplate.opsForValue().get("user"), User.class);
}
@PostMapping("/users")
public Object addUsers(@RequestBody List<User> users){
stringRedisTemplate.opsForList().rightPushAll("users", users.stream().map(JSON::toJSONString).collect(Collectors.toList()));
return "success";
}
@GetMapping("/users")
public Object getUsers(){
List<User> users = new ArrayList<>();
while (true){
User user = JSON.parseObject(stringRedisTemplate.opsForList().leftPop("users"), User.class);
if (Objects.isNull(user)) {
break;
}
users.add(user);
}
return users;
}
}
PS
如果在項目啟動或者調用接口時報錯,提示無法連接Redis,可以對redis.conf做如下配置。在redis的安裝目錄修改配置文件
vim redis.conf
bind 127.0.0.1 改為 bind 0.0.0.0 表示允許任何連接
protected-mode yes 改為 protected-mode no 表示關閉保護模式
然后關閉redis后,使用新的配置文件啟動redis-server。在Redis的目錄
src/redis-server redis.conf
項目源碼在:https://github.com/AganRun/Learn/tree/master/SpringBoot-Redis