如何使用StringRedisTemplate操作Redis詳解

如何使用StringRedisTemplate操作Redis詳解

Redis簡介

Redis 是一個開源(BSD許可)的,內存中的數據結構存儲系統,它可以用作數據庫、緩存和消息中間件。支持事務5.0版本新增stream數據類型。

Spring boot單數據源配置

Springboot的redis單數據源配置特別簡單
(1)配置appliation.properties文件

spring.redis.host=x.x.x.x
spring.redis.port=6379
#redis的數據庫號
spring.redis.database=4
spring.redis.timeout = 30000ms
spring.redis.jedis.pool.max-active=200
spring.redis.jedis.pool.max-idle=0
spring.redis.lettuce.pool.max-idle=5
spring.redis.jedis.pool.max-wait=20000ms

(2)StringRedisTemplate的基本操作


StringRedisTemplate自動關閉redis連接
//注入對象     
@Autowired
private StringRedisTemplate stringRedisTemplate;

#獲取ValueOperations操作String數據
ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
valueOperations.set("strRedis","StringRedisTemplate");
valueOperations.get("strRedis"); 

#設置過期時間     
set("timeStep", new Date().getTime()+"", 2 ,TimeUnit.MINUTES);

#獲取SetOperations操作Set數據
 SetOperations<String, String> set = stringRedisTemplate.opsForSet();
 set.add("set1","22");
 set.add("set1","33");
 set.add("set1","44");
 Set<String> resultSet =stringRedisTemplate.opsForSet().members("set1");
 stringRedisTemplate.opsForSet().add("set2", "1","2","3");//向指定key中存放set集合
 Set<String> resultSet1 =stringRedisTemplate.opsForSet().members("set2");
 log.info("resultSet:"+resultSet);
 log.info("resultSet1:"+resultSet1);

#獲取ListOperations操作List數據,list可以用來實現隊列。
 //將數據添加到key對應的現有數據的左邊
 Long redisList = stringRedisTemplate.opsForList().leftPush("redisList", "3");
 stringRedisTemplate.opsForList().leftPush("redisList", "4");
 //將數據添加到key對應的現有數據的右邊
 Long size = stringRedisTemplate.opsForList().size("redisList");
 //從左往右遍歷
 String leftPop = stringRedisTemplate.opsForList().leftPop("redisList");
 //從右往左遍歷
 String rightPop = stringRedisTemplate.opsForList().rightPop("redisList");
 //查詢全部元素
 List<String> range = stringRedisTemplate.opsForList().range("redisList", 0, -1);
 //查詢前三個元素
 List<String> range1 = stringRedisTemplate.opsForList().range("redisList", 0, 3);
 //從左往右刪除list中元素A  (1:從左往右 -1:從右往左 0:刪除全部)
 Long remove = stringRedisTemplate.opsForList().remove("key", 1, "A");
 log.info("redisList----"+redisList);
 log.info("size----"+size);
 log.info("leftPop----"+leftPop);
 log.info("rightPop----"+rightPop);
 log.info("range----"+range);
 log.info("range1----"+range1);
 log.info("remove----"+remove);  

//判斷key對應的map中是否存在hash
Boolean aBoolean = stringRedisTemplate.opsForHash().hasKey("hash", "hash1");
//往key對應的map中新增(key1,value1)
stringRedisTemplate.opsForHash().put("hash", "hash1", "value1");
//獲取key對應的map中hash1的值
Object o = stringRedisTemplate.opsForHash().get("hash", "hash1");
//刪除key對應的map中多個子hash(可變參數)
Long delete = stringRedisTemplate.opsForHash().delete("hash", "key1", "key2", "key3");
//獲取hash對應的map
Map<Object, Object> hash = stringRedisTemplate.opsForHash().entries("hash");
//獲取hash對應的map中全部子hash集合
Set<Object> hash1 = stringRedisTemplate.opsForHash().keys("hash");
//獲取hash對應的map中全部value集合
List<Object> hash2 = stringRedisTemplate.opsForHash().values("hash");

#刪除鍵
Boolean key = stringRedisTemplate.delete("key");  
#數字加x
Long count = stringRedisTemplate.boundValueOps("count").increment(1);//val +1 
#獲取過期時間,不設的話爲-1
Long time = stringRedisTemplate.getExpire("count")   
  
   

Spring boot多數據源配置,配置一個1號庫,一個4號庫

添加依賴


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

修改application.properties配置文件


#1號庫
spring.redis.redis-onedb.database=0
spring.redis.redis-onedb.hostName=192.168.90.42
spring.redis.redis-onedb.port=9110
spring.redis.redis-onedb.timeout=5000
#4號庫
spring.redis.redis-fourdb.database=4
spring.redis.redis-fourdb.hostName=192.168.90.42
spring.redis.redis-fourdb.port=9110
spring.redis.redis-fourdb.timeout=5000

創建RedisConfig.java文件

@Configuration
public class RedisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.redis.lettuce.pool")
@Scope(value = "prototype")
public GenericObjectPoolConfig redisPool(){
    return new GenericObjectPoolConfig();
}

@Bean
@ConfigurationProperties(prefix = "spring.redis.redis-fourdb")
public RedisStandaloneConfiguration redisConfigA(){
    return new RedisStandaloneConfiguration();
}

@Bean
@ConfigurationProperties(prefix = "spring.redis.redis-onedb")
public RedisStandaloneConfiguration redisConfigB(){
    return new RedisStandaloneConfiguration();
}

@Primary
@Bean
public LettuceConnectionFactory factoryA(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigA){
    LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
            .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build();
    return new LettuceConnectionFactory(redisConfigA, clientConfiguration);
}

@Bean
public LettuceConnectionFactory factoryB(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConfigB){
    LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
            .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build();
    return new LettuceConnectionFactory(redisConfigB, clientConfiguration);
}


@Bean(name = "fourRedis")
public StringRedisTemplate redisBusTemplate(@Qualifier("factoryA") LettuceConnectionFactory factoryA){
    StringRedisTemplate template = getRedisTemplate();
    template.setConnectionFactory(factoryA);
    return template;
}

@Bean(name = "oneRedis")
public StringRedisTemplate redisLoginTemplate(@Qualifier("factoryB")LettuceConnectionFactory factoryB){
    StringRedisTemplate template = getRedisTemplate();
    template.setConnectionFactory(factoryB);
    return template;
}

private StringRedisTemplate getRedisTemplate(){
    StringRedisTemplate template = new StringRedisTemplate();
    template.setValueSerializer(new GenericFastJsonRedisSerializer());
    template.setValueSerializer(new StringRedisSerializer());
    return template;
}
}

在需要使用的類,注入就可以使用

@Resource(name = "oneRedis")
private StringRedisTemplate oneRedis;

@Resource(name = "fourRedis")
private StringRedisTemplate fourRedis;

StringRedisTemplate實現事務

stringRedisTemplate.setEnableTransactionSupport(true);
    try {
        stringRedisTemplate.multi();//開啓事務
        stringRedisTemplate.opsForValue().increment("count", 1);
        stringRedisTemplate.opsForValue().increment("count1", 2);
        //提交
        stringRedisTemplate.exec();
    }catch (Exception e){
        log.error(e.getMessage(), e);
        //開啓回滾
        stringRedisTemplate.discard();
    }

注意:StringRedisTemplate開啓事務之後,不釋放連接。如果我們使用Spring事務管理不存在這個問題

StringRedisTemplate實現樂觀鎖

redisTemplate.watch("key"); // 1
redisTemplate.multi();
redisTemplate.boundValueOps("key").set(""+id);
List<Object> list= redisTemplate.exec();
System.out.println(list);
if(list != null ){
    //操作成功
    System.out.println(id+"操作成功");
}else{
    //操作失敗
    System.out.println(id+"操作失敗");
}

StringRedisTemplate實現pipe管道

StringRedisTemplate實現分佈式鎖

String lockKey = "key";
String lockValue = lockKey+System.currentTimeMillis();
// value需要記住用於解鎖
while (true){

   Boolean ifPresent = stringRedisTemplate.opsForValue().
                setIfAbsent("redis-lock:" + lockKey, lockValue, 3, TimeUnit.SECONDS);

   if (ifPresent){
          log.info("get redis-lock success");
          break;
    }
 }
//解鎖
  String lockKey = "key";
 String lockValue = lockKey + System.currentTimeMillis();
 boolean result = false;
 // value需要記住用於解鎖
 stringRedisTemplate.watch("redis-lock:" + lockKey);
 String value = stringRedisTemplate.opsForValue().get("redis-lock:" + lockKey);
 if (null == value){
     result = true;
 }else if (value.equals(lockValue)) {
     stringRedisTemplate.delete("redis-lock:" + lockKey);
     result = true;
 }
 stringRedisTemplate.unwatch();  

Redis緩存擊穿、穿透和雪崩

緩存擊穿,是指一個key非常熱點,在不停的扛着大併發,大併發集中對這一個點進
行訪問,當這個key在失效的瞬間,持續的大併發就穿破緩存,直接請求數據庫,就
像在一個屏障上鑿開了一個洞
      
緩存穿透,是指查詢一個數據庫一定不存在的數據。正常的使用緩存流程大致是,
數據查詢先進行緩存查詢,如果key不存在或者key已經過期,再對數據庫進行查
詢,並把查詢到的對象,放進緩存。如果數據庫查詢對象爲空,則不放進緩存。
解決辦法是即使查出的對象爲空,也放入緩存時間設短一點。

緩存雪崩,是指在某一個時間段,緩存集中過期失效。

有問題,請留言!

個人博客地址 王開金的博客

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