spring-boot-route(十二)整合redis做為緩存


redis簡介

redis作為一種非關系型數據庫,讀寫非常快,應用十分廣泛,它采用key-value的形式存儲數據,value常用的五大數據類型有string(字符串),list(鏈表),set(集合),zset(有序集合)和hash(哈希表)。

redis的特性決定了它的功能,它可以用來做以下這些事情!

  1. 排行榜,利用zset可以方便的實現排序功能
  2. 計數器,利用redis中原子性的自增操作,可以統計到閱讀量,點贊量等功能
  3. 簡單消息隊列,list存儲結構,滿足先進先出的原則,可以使用lpush/rpop或rpush/lpop實現簡單消息隊列
  4. session共享,分布式系統中,可以利用redis實現session共享。spring官方提供的分布式解決方案Spring Session就是利用redis 實現的。

Spring Boot對redis也實現自動化裝配,使用非常方便。

Spring Boot整合redis

1. 引入redis依賴

<dependencies>
    <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>
</dependencies>

2. 配置redis相關信息

spring:
  redis:
    # redis庫
    database: 0
    # redis 服務器地址
    host: localhost
    # redis 端口號
    port: 6379
    # redis 密碼
    password:
    # 連接超時時間(毫秒)
    timeout: 1000
    lettuce:
      pool:
        # 連接池最大鏈接數(負數表示沒有限制)
        max-active: 8
        # 連接池最大阻塞等待時間(負數表示沒有限制)
        max-wait: -1
        # 連接池最大空閑連接數
        max-idle: 8
        # 連接池最小空閑連接數
        min-idle: 0

3. 操作redis

SpringBoot提供了兩個bean來操作redis,分別是RedisTemplateStringRedisTemplate,這兩者的主要區別如下。

RedisTemplate使用的是JdkSerializationRedisSerializer 存入數據會將數據先序列化成字節數組然后在存入Redis數據庫。

StringRedisTemplate使用的是StringRedisSerializer。

下面一起來看看效果:

@RestController
public class RedisDemo {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("redisTmeplateData")
    public void redisTemplateData(){

        redisTemplate.opsForValue().set("name","Java旅途");
    }

    @GetMapping("stringRedisTemplateData")
    public void stringRedisTemplateData(){

        stringRedisTemplate.opsForValue().set("desc","堅持分享java技術棧");
    }
}

第一個方法存入的數據如下圖

第二個方法存入的數據如下圖

由於RedisTemplate是序列化成字節數組存儲的,因此在redis客戶端的可讀性並不好。

自動緩存

@Cacheable可以標記在一個方法上,也可以標記在一個類上。當標記在一個方法上時表示該方法是支持緩存的,當標記在一個類上時則表示該類所有的方法都是支持緩存的。

如果添加了@Cacheable注解,那么方法被調用后,值會被存入redis,下次再調用的時候會直接從redis中取值返回。

@GetMapping("getStudent")
@Cacheable(value = "student:key")
public Student getStudent(){
    log.info("我不是緩存,我是new的對象!");
    Student student = new Student("Java旅途",26);
    return student;
}

記得要開啟緩存,在啟動類加上@EnableCaching注解

訪問上面的方法,如果不打印日志,則是從緩存中獲取的值。

封裝redisUtils

RedisTemplate提供了很多方法來操作redis,但是找起來比較費事,為了更好的操作redis,一般會封裝redisUtils來滿足業務開發。這里簡單封裝幾個做個示例,如果開發中有需求可以自己封裝。

public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 普通存入
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通獲取key
     * @param key
     * @return
     */
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 存入key,設置過期時長
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key,Object value,long time){
        try {
            if(time > 0){
                redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
            }else{
                redisTemplate.opsForValue().set(key,value);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判斷key是否存在
     * @param key
     * @return
     */
    public boolean exists(String key){
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 刪除key
     * @param key
     */
    public void del(String key){
        try {
            if(key != null && key.length() > 0){
                redisTemplate.delete(key);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

本文示例代碼已上傳至github,點個star支持一下!

Spring Boot系列教程目錄

spring-boot-route(一)Controller接收參數的幾種方式

spring-boot-route(二)讀取配置文件的幾種方式

spring-boot-route(三)實現多文件上傳

spring-boot-route(四)全局異常處理

spring-boot-route(五)整合swagger生成接口文檔

spring-boot-route(六)整合JApiDocs生成接口文檔

spring-boot-route(七)整合jdbcTemplate操作數據庫

spring-boot-route(八)整合mybatis操作數據庫

spring-boot-route(九)整合JPA操作數據庫

spring-boot-route(十)多數據源切換

spring-boot-route(十一)數據庫配置信息加密

spring-boot-route(十二)整合redis做為緩存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

spring-boot-route(十五)整合RocketMQ

spring-boot-route(十六)使用logback生產日志文件

spring-boot-route(十七)使用aop記錄操作日志

spring-boot-route(十八)spring-boot-adtuator監控應用

spring-boot-route(十九)spring-boot-admin監控服務

spring-boot-route(二十)Spring Task實現簡單定時任務

spring-boot-route(二十一)quartz實現動態定時任務

spring-boot-route(二十二)實現郵件發送功能

spring-boot-route(二十三)開發微信公眾號

spring-boot-route(二十四)分布式session的一致性處理

spring-boot-route(二十五)兩行代碼實現國際化

spring-boot-route(二十六)整合webSocket

這個系列的文章都是工作中頻繁用到的知識,學完這個系列,應付日常開發綽綽有余。如果還想了解其他內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM