5

实例讲解Springboot以Repository方式整合Redis

 2 years ago
source link: https://www.pkslow.com/archives/springboot-redis-repository
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Redis是高性能的NoSQL数据库,经常作为缓存流行于各大互联网架构中。本文将介绍如何在Springboot中整合Spring Data Redis,使用Repository的方式操作。

代码结构如下:

2 整合过程

2.1 安装Redis数据库

为了节省时间,就直接通过Docker来安装了,可以参考文章:Docker安装Redis并介绍漂亮的可视化客户端进行操作,可以快速安装并使用客户端进行查看和操作。

2.2 引入相关依赖

我们引入Springboot Web的依赖,以启动REST服务。还需要引入Spring Data Redis相关的依赖。最后,还需要commons-pool2,不然会因为缺少类而无法启动。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>

2.3 配置连接信息

配置Redis的连接信息,这个信息跟你安装时的配置有关,同时配置了连接池,各项的配置及相关解释如下:

# Redis数据库索引,默认为0
spring.redis.database=0
# Redis端口
spring.redis.port=6379
# Redis服务器主机
spring.redis.host=localhost
# 连接池最大连接数
spring.redis.lettuce.pool.max-active=8
# 连接池最大空闲
spring.redis.lettuce.pool.max-idle=8
# 连接池最小空闲
spring.redis.lettuce.pool.min-idle=2
# 连接池最大阻塞等待时间
spring.redis.lettuce.pool.max-wait=1ms
# 超时时间
spring.redis.lettuce.shutdown-timeout=100ms

2.4 创建实体类

存入Redis中的数据类型,可以是自定义的一个类,注意需要加上注解@RedisHash@Id。存入Redis的数据为Set类型。

具体代码如下:

package com.pkslow.redis.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import java.util.Date;

@RedisHash("User")
public class User {
    @Id
    private String userId;
    private String name;
    private Integer age;
    private Date createTime = new Date();

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

2.5 数据库访问层UserRepository接口

直接继承CrudRepository接口就行了,不用自己来实现,需要注意CrudRepository<User, String>的泛型类型:

package com.pkslow.redis.dal;

import com.pkslow.redis.model.User;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, String> {
}

2.6 实现Controller

Controller实现了RESTful风格的增删改查功能,只要把UserRepository注入便可以使用它来操作:

package com.pkslow.redis.controller;

import com.pkslow.redis.dal.UserRepository;
import com.pkslow.redis.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private final UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("")
    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/{userId}")
    public User getByUserId(@PathVariable String userId) {
        return userRepository.findById(userId).orElse(new User());
    }

    @PostMapping("")
    public User addNewUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @DeleteMapping("/{userId}")
    public String delete(@PathVariable String userId) {
        User user = new User();
        user.setUserId(userId);
        userRepository.deleteById(userId);
        return "deleted: " + userId;
    }

    @PutMapping("")
    public User update(@RequestBody User user) {
        return userRepository.save(user);
    }
}

3 Postman接口测试

本文使用Postman进行测试,结果显示的时间为GMT时间,每个功能测试如下:

(1)新增User

(2)根据UserId查询特定User

(3)修改User

(4)删除一个User

(5)查询所有User

Redis中的数据如下所示:

本文通过实例讲解了如何整合SpringbootRedis,使用的是Repository的方式。详细代码可在南瓜慢说公众号回复<SpringbootRedisRepository>获取。


欢迎关注微信公众号<南瓜慢说>,将持续为你更新...

推荐阅读:
如何制定切实可行的计划并好好执行
容器技术(Docker-Kubernetes)
SpringBoot-Cloud相关
Https专题


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK