通過@RedisHash註解存儲實體到redis

新建一個實體,使用@RedisHash註解標識

如下代碼: 在實體中需要將某個屬性標識爲唯一id,**添加@Id註解;**然而如果需要該實體在redis存儲中擁有生命週期,添加@TimeToLive註解;以秒爲單位,可根據需要設置其失效時間;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.TimeToLive;
/**
 * @author: SUN
 * @version: 1.0
 * @date: 2020/3/20 15:49
 * @description:
 */
@RedisHash
@Data
public class TestEntity {
    @Id
    private String phone;
    private String name;
    @TimeToLive
    private Long time;
}

新建Dao層接口,並繼承CrudRepository接口實現相關方法

import com.touchspring.isite.base.entity.TestEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * @author: SUN
 * @version: 1.0
 * @date: 2020/3/20 15:53
 * @description:
 */

@Repository
public interface TestEntityDao extends CrudRepository<TestEntity, String> {
}

然後通過控制層進行接口測試

  • 首先進行存儲操作,通過調用 testEntityDao接口下面的save()方法進行實現。
  @PostMapping(value = "/test/save")
    public ResultData testEntity() {
        TestEntity testEntity = new TestEntity();
        testEntity.setPhone("18803838082");
        testEntity.setName("sun");
        testEntity.setTime(60L);
        testEntityDao.save(testEntity);
        return ResultData.ok();
    }

如下圖所示,通過條用接口方法即可將數據保存至redis中,並在有效時間內可通過get方法進行讀取。本次設置時長爲60秒。
在這裏插入圖片描述

  • 下面將通過GET請求進行數據讀取,若設置時間未過期,將可以根據設置的@Id 進行讀取。
       @PostMapping(value = "/test/get")
    public ResultData testEntity1() {
        Optional<TestEntity> optionalTestEntity = testEntityDao.findById("18803838082");
        if (optionalTestEntity.isPresent()) {
            TestEntity testEntity = optionalTestEntity.get();
            System.out.println(" - --  -" + testEntity.getName());
            System.out.println(" - --  -" + testEntity.getPhone());
            System.out.println(" - --  -" + testEntity.getTime());
            return ResultData.ok().putDataValue("testEntity", testEntity);

        } else {
            return new ResultData(1500, "數據信息不存在,或已過期");
        }
    }
 

如下圖,我們讀取的結果中,time字段的值存在變化,此時返回的值是該條數據的生命週期剩餘時間,單位S秒。
在這裏插入圖片描述
如果超出時間將返回如下信息
在這裏插入圖片描述
至此,我們完成了通過@RedisHash註解和繼承**CrudRepository<TestEntity, String>**接口實現了redis存儲數據,並設置了數據信息的生命週期,此方法適用於驗證碼校對時進行有效期驗證。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章