SpringDataRedis快速开发

一、pom.xml中引入SpringDataRedis相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

二、修改application.yml    添加spring.redis...

server: 
  port: 9004
spring: 
  application:  
    name: csdnblog-article #指定服务名
  datasource:  
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/csdnblog_article?characterEncoding=UTF8
    username: root
    password: root
  jpa: 
    database: MySQL
    show-sql: true
  redis:
    host: 10.211.55.28
    password: ZPzp2309413@
    port: 6379

 

三、注入RestTemplate

@AutoWired
private RestTemplate restTemplate;

四、使用缓存的思路

(1)先查缓存,存在直接返回redis中的数据

(2)缓存中不存在则查询数据库,得到数据结果集

(3)容易遗漏的一点:将数据库中查询的结果放入redis中,并设置合理的过期时间

(4)返回结果

在进行修改和删除操作时候,不要忘记删除redis中的数据

五、常用代码

5.1 向redis里存入数据和设置缓存时间

//key:"test"  value:"100" 过期时间60*10秒
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);

5.2 根据key获取缓存中的val

//通过key:"test"获取value值
stringRedisTemplate.opsForValue().get("test");

5.3  val做-1/+1操作

stringRedisTemplate.boundValueOps("test").increment(-1);  //val -1
stringRedisTemplate.boundValueOps("test").increment(1);   //val +1

5.4 根据key获取过期时间

stringRedisTemplate.getExpire("test");

5.5 根据key获取过期时间并换算成指定单位

stringRedisTemplate.getExpire("test",TimeUnit.SECONDS);

5.6 根据key删除缓存

stringRedisTemplate.delete("test");

5.7 检查key是否存在,返回boolean值

stringRedisTemplate.hasKey("546545");

5.8 设置过期时间

stringRedisTemplate.expire("red_123",1000 ,TimeUnit.MILLISECONDS);

5.9 向指定key中存放set集合

stringRedisTemplate.opsForSet().add("red_123", "1","2","3");

5.10 根据key查看集合中是否存在指定数据

stringRedisTemplate.opsForSet().isMember("red_123", "1");

5.11 根据key获取set集合

stringRedisTemplate.opsForSet().members("red_123");
发布了162 篇原创文章 · 获赞 237 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/itcats_cn/article/details/87949136