通过@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存储数据,并设置了数据信息的生命周期,此方法适用于验证码校对时进行有效期验证。