SpringBoot+Redis简单使用

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

猜你喜欢

转载自www.cnblogs.com/AganRun/p/11823947.html