天天看點

SpringBoot整合Redis,你get了嗎?

Our-task介紹

本篇部落格是我github上

our-task:一個完整的清單管理系統

的配套教程文檔,這是SpringBoot+Vue開發的前後端分離清單管理工具,仿滴答清單。目前已部署在阿裡雲ECS上,可進行線上預覽,随意使用(附詳細教程),大家感興趣的話,歡迎給個star!

阿裡雲預覽位址

Redis的安裝與配置

Windows下redis的安裝與配置

SpringBoot整合Redis

添加項目依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!--redis依賴配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>           

yml檔案配置

yml檔案中主要是關于Redis的配置,其中鍵的設定格式為:資料庫名:表名:id,更多Redis了解,請大家參考這篇文章。

Redis各種鍵的典型使用場景,不清楚的都來看一下
# DataSource Config
spring:
  redis:
    # Redis伺服器位址
    host: localhost
    # Redis資料庫索引(預設為0)
    database: 0
    # Redis伺服器連接配接端口
    port: 6379
    # Redis伺服器連接配接密碼(預設為空)
    password:
    jedis:
      pool:
        # 連接配接池最大連接配接數(使用負值表示沒有限制)
        max-active: 8
        # 連接配接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: -1ms
        # 連接配接池中的最大空閑連接配接
        max-idle: 8
        # 連接配接池中的最小空閑連接配接
        min-idle: 0
    # 連接配接逾時時間(毫秒)
    timeout: 3000ms

# 自定義redis key
redis:
  database: "study"
  key:
    user: "user"
  expire:
    common: 86400 # 24小時           

實體類

建立entity包,在該包下建立User類,用作該Demo的操作實體。考慮到一些小白可能還不了解Lombok,我就直接使用Setter/Getter。

package com.example.demo.entity;

/**
 * @program: SpringBoot-Redis-Demo
 * @description: 使用者類
 * @author: water76016
 * @create: 2020-12-29 09:22
 **/
public class User {
    Integer id;
    String username;
    String password;

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}           

Service服務接口

服務接口一共有兩個:一個是UserService,一個是RedisService。UserService提供了針對User實體的服務,RedisService提供操作Reids的服務接口。

package com.example.demo.service;

import com.example.demo.entity.User;

public interface UserService {
    /**
     * 對使用者打招呼,傳回user的toString()方法
     * @param user
     * @return
     */
    public String helloUser(User user);
}           
package com.example.demo.service;

import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @program: our-task
 * @description: redis操作服務類
 * @author: water76016
 * @create: 2020-09-24 16:45
 **/
public interface RedisService {

    /**
     * 儲存屬性
     *
     * @param key   the key
     * @param value the value
     * @param time  the time
     */
    void set(String key, Object value, long time);

    /**
     * 儲存屬性
     *
     * @param key   鍵
     * @param value 值
     */
    void set(String key, Object value);

    /**
     * 擷取屬性
     *
     * @param key the key
     * @return the object
     */
    Object get(String key);

    /**
     * 删除屬性
     *
     * @param key the key
     * @return the boolean
     */
    Boolean del(String key);

    /**
     * 批量删除屬性
     *
     * @param keys the keys
     * @return the long
     */
    Long del(List<String> keys);

    /**
     * 設定過期時間
     *
     * @param key  the key
     * @param time the time
     * @return the boolean
     */
    Boolean expire(String key, long time);

    /**
     * 擷取過期時間
     *
     * @param key the key
     * @return the expire
     */
    Long getExpire(String key);

    /**
     * 判斷是否有該屬性
     *
     * @param key the key
     * @return the boolean
     */
    Boolean hasKey(String key);

    /**
     * 按delta遞增
     *
     * @param key   the key
     * @param delta the delta
     * @return the long
     */
    Long incr(String key, long delta);

    /**
     * 按delta遞減
     *
     * @param key   the key
     * @param delta the delta
     * @return the long
     */
    Long decr(String key, long delta);

    /**
     * 擷取Hash結構中的屬性
     *
     * @param key     the key
     * @param hashKey the hash key
     * @return the object
     */
    Object hGet(String key, String hashKey);

    /**
     * 向Hash結構中放入一個屬性
     *
     * @param key     the key
     * @param hashKey the hash key
     * @param value   the value
     * @param time    the time
     * @return the boolean
     */
    Boolean hSet(String key, String hashKey, Object value, long time);

    /**
     * 向Hash結構中放入一個屬性
     *
     * @param key     the key
     * @param hashKey the hash key
     * @param value   the value
     */
    void hSet(String key, String hashKey, Object value);

    /**
     * 直接擷取整個Hash結構
     *
     * @param key the key
     * @return the map
     */
    Map<Object, Object> hGetAll(String key);

    /**
     * 直接設定整個Hash結構
     *
     * @param key  the key
     * @param map  the map
     * @param time the time
     * @return the boolean
     */
    Boolean hSetAll(String key, Map<String, Object> map, long time);

    /**
     * 直接設定整個Hash結構
     *
     * @param key the key
     * @param map the map
     */
    void hSetAll(String key, Map<String, Object> map);

    /**
     * 删除Hash結構中的屬性
     *
     * @param key     the key
     * @param hashKey the hash key
     */
    void hDel(String key, Object... hashKey);

    /**
     * 判斷Hash結構中是否有該屬性
     *
     * @param key     the key
     * @param hashKey the hash key
     * @return the boolean
     */
    Boolean hHasKey(String key, String hashKey);

    /**
     * Hash結構中屬性遞增
     *
     * @param key     the key
     * @param hashKey the hash key
     * @param delta   the delta
     * @return the long
     */
    Long hIncr(String key, String hashKey, Long delta);

    /**
     * Hash結構中屬性遞減
     *
     * @param key     the key
     * @param hashKey the hash key
     * @param delta   the delta
     * @return the long
     */
    Long hDecr(String key, String hashKey, Long delta);

    /**
     * 擷取Set結構
     *
     * @param key the key
     * @return the set
     */
    Set<Object> sMembers(String key);

    /**
     * 向Set結構中添加屬性
     *
     * @param key    the key
     * @param values the values
     * @return the long
     */
    Long sAdd(String key, Object... values);

    /**
     * 向Set結構中添加屬性
     *
     * @param key    the key
     * @param time   the time
     * @param values the values
     * @return the long
     */
    Long sAdd(String key, long time, Object... values);

    /**
     * 是否為Set中的屬性
     *
     * @param key   the key
     * @param value the value
     * @return the boolean
     */
    Boolean sIsMember(String key, Object value);

    /**
     * 擷取Set結構的長度
     *
     * @param key the key
     * @return the long
     */
    Long sSize(String key);

    /**
     * 删除Set結構中的屬性
     *
     * @param key    the key
     * @param values the values
     * @return the long
     */
    Long sRemove(String key, Object... values);

    /**
     * 擷取List結構中的屬性
     *
     * @param key   the key
     * @param start the start
     * @param end   the end
     * @return the list
     */
    List<Object> lRange(String key, long start, long end);

    /**
     * 擷取List結構的長度
     *
     * @param key the key
     * @return the long
     */
    Long lSize(String key);

    /**
     * 根據索引擷取List中的屬性
     *
     * @param key   the key
     * @param index the index
     * @return the object
     */
    Object lIndex(String key, long index);

    /**
     * 向List結構中添加屬性
     *
     * @param key   the key
     * @param value the value
     * @return the long
     */
    Long lPush(String key, Object value);

    /**
     * 向List結構中添加屬性
     *
     * @param key   the key
     * @param value the value
     * @param time  the time
     * @return the long
     */
    Long lPush(String key, Object value, long time);

    /**
     * 向List結構中批量添加屬性
     *
     * @param key    the key
     * @param values the values
     * @return the long
     */
    Long lPushAll(String key, Object... values);

    /**
     * 向List結構中批量添加屬性
     *
     * @param key    the key
     * @param time   the time
     * @param values the values
     * @return the long
     */
    Long lPushAll(String key, Long time, Object... values);

    /**
     * 從List結構中移除屬性
     *
     * @param key   the key
     * @param count the count
     * @param value the value
     * @return the long
     */
    Long lRemove(String key, long count, Object value);
}           

Service實作類

在UserService中,我們把使用者的資訊存儲在Redis中。調用了RedisService的方法,同時給該鍵設定過期時間。大家在操作的時候,直接使用RedisService中的方法就可以了,這些方法還是挺全的。

package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.service.RedisService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @program: SpringBoot-Redis-Demo
 * @description: 使用者服務實作類
 * @author: water76016
 * @create: 2020-12-29 09:24
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    RedisService redisService;

    @Value("${redis.database}")
    private String redisDatabase;
    @Value("${redis.key.user}")
    private String redisUserKey;
    @Value("${redis.expire.common}")
    private long expire;
    /**
     * 對使用者打招呼,傳回user的toString()方法
     *
     * @param user
     * @return
     */
    @Override
    public String helloUser(User user) {
        //設定鍵,鍵的格式為:資料庫名:user:使用者id
        String key = redisDatabase + ":" + redisUserKey + ":" + user.getId();
        //把使用者的toString,存在這個鍵裡面
        redisService.set(key, user.toString());
        //設定鍵的過期時間
        redisService.expire(key, expire);
        return user.toString();
    }
}           
package com.example.demo.service.impl;

import com.example.demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @program: our-task
 * @description: redis操作服務接口實作類
 * @author: water76016
 * @create: 2020-09-24 16:45
 **/
@Service
public class RedisServiceImpl implements RedisService {
    /**
     * 由于沒有指定具體類型<String, Object>,用Resource注入才有效
     * */
    @Resource
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }
    
    @Override
    public void set(String key, Object value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    @Override
    public void set(String key, Object value) {

        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public Long del(List<String> keys) {
        return redisTemplate.delete(keys);
    }

    @Override
    public Boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    @Override
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public Long incr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    @Override
    public Long decr(String key, long delta) {
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    @Override
    public Object hGet(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    @Override
    public Boolean hSet(String key, String hashKey, Object value, long time) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return expire(key, time);
    }

    @Override
    public void hSet(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

    @Override
    public Map<Object, Object> hGetAll(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Override
    public Boolean hSetAll(String key, Map<String, Object> map, long time) {
        redisTemplate.opsForHash().putAll(key, map);
        return expire(key, time);
    }

    @Override
    public void hSetAll(String key, Map<String, Object> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }

    @Override
    public void hDel(String key, Object... hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    @Override
    public Boolean hHasKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    @Override
    public Long hIncr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, delta);
    }

    @Override
    public Long hDecr(String key, String hashKey, Long delta) {
        return redisTemplate.opsForHash().increment(key, hashKey, -delta);
    }

    @Override
    public Set<Object> sMembers(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    @Override
    public Long sAdd(String key, Object... values) {
        return redisTemplate.opsForSet().add(key, values);
    }

    @Override
    public Long sAdd(String key, long time, Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Boolean sIsMember(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    @Override
    public Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public Long sRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    @Override
    public List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    @Override
    public Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    @Override
    public Object lIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    @Override
    public Long lPush(String key, Object value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    @Override
    public Long lPush(String key, Object value, long time) {
        Long index = redisTemplate.opsForList().rightPush(key, value);
        expire(key, time);
        return index;
    }

    @Override
    public Long lPushAll(String key, Object... values) {
        return redisTemplate.opsForList().rightPushAll(key, values);
    }

    @Override
    public Long lPushAll(String key, Long time, Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        expire(key, time);
        return count;
    }

    @Override
    public Long lRemove(String key, long count, Object value) {
        return redisTemplate.opsForList().remove(key, count, value);
    }
}           

UserController控制器

接下來,我們建立一個controller包,在該包下建立UserController控制類。

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @program: SpringBoot-Redis-Demo
 * @description:
 * @author: water76016
 * @create: 2020-12-29 09:27
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/helloUser")
    public String helloUser(@RequestBody User user){
        return userService.helloUser(user);
    }

}           

結果測試

最後,我們啟動SpringBoot程式,程式運作在8080端口,在postman中進行測試。大家按照我在postman中的輸入,就會有相應的輸出了。

SpringBoot整合Redis,你get了嗎?

另外,也來看看Redis中是否有相應的緩存結果。

SpringBoot整合Redis,你get了嗎?

Demo位址

寫了這麼多,還是擔心大家使用的時候有問題,是以我把該Demo放在了Github上,大家自行下載下傳就可以了。

SpringBoot-Redis-Demo位址