亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

如何使用StringRedisTemplate操作Redis詳解

tulayang / 3632人閱讀

摘要:如何使用操作詳解簡(jiǎn)介是一個(gè)開(kāi)源許可的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)系統(tǒng),它可以用作數(shù)據(jù)庫(kù)緩存和消息中間件。解決辦法是即使查出的對(duì)象為空,也放入緩存時(shí)間設(shè)短一點(diǎn)。緩存雪崩,是指在某一個(gè)時(shí)間段,緩存集中過(guò)期失效。

如何使用StringRedisTemplate操作Redis詳解 Redis簡(jiǎn)介

Redis 是一個(gè)開(kāi)源(BSD許可)的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)系統(tǒng),它可以用作數(shù)據(jù)庫(kù)、緩存和消息中間件。支持事務(wù)5.0版本新增stream數(shù)據(jù)類型。

Spring boot單數(shù)據(jù)源配置

Springboot的redis單數(shù)據(jù)源配置特別簡(jiǎn)單
(1)配置appliation.properties文件

spring.redis.host=x.x.x.x
spring.redis.port=6379
#redis的數(shù)據(jù)庫(kù)號(hào)
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自動(dòng)關(guān)閉redis連接
//注入對(duì)象     
@Autowired
private StringRedisTemplate stringRedisTemplate;

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

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

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

#獲取ListOperations操作List數(shù)據(jù),list可以用來(lái)實(shí)現(xiàn)隊(duì)列。
 //將數(shù)據(jù)添加到key對(duì)應(yīng)的現(xiàn)有數(shù)據(jù)的左邊
 Long redisList = stringRedisTemplate.opsForList().leftPush("redisList", "3");
 stringRedisTemplate.opsForList().leftPush("redisList", "4");
 //將數(shù)據(jù)添加到key對(duì)應(yīng)的現(xiàn)有數(shù)據(jù)的右邊
 Long size = stringRedisTemplate.opsForList().size("redisList");
 //從左往右遍歷
 String leftPop = stringRedisTemplate.opsForList().leftPop("redisList");
 //從右往左遍歷
 String rightPop = stringRedisTemplate.opsForList().rightPop("redisList");
 //查詢?nèi)吭? List range = stringRedisTemplate.opsForList().range("redisList", 0, -1);
 //查詢前三個(gè)元素
 List 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對(duì)應(yīng)的map中是否存在hash
Boolean aBoolean = stringRedisTemplate.opsForHash().hasKey("hash", "hash1");
//往key對(duì)應(yīng)的map中新增(key1,value1)
stringRedisTemplate.opsForHash().put("hash", "hash1", "value1");
//獲取key對(duì)應(yīng)的map中hash1的值
Object o = stringRedisTemplate.opsForHash().get("hash", "hash1");
//刪除key對(duì)應(yīng)的map中多個(gè)子hash(可變參數(shù))
Long delete = stringRedisTemplate.opsForHash().delete("hash", "key1", "key2", "key3");
//獲取hash對(duì)應(yīng)的map
Map hash = stringRedisTemplate.opsForHash().entries("hash");
//獲取hash對(duì)應(yīng)的map中全部子hash集合
Set hash1 = stringRedisTemplate.opsForHash().keys("hash");
//獲取hash對(duì)應(yīng)的map中全部value集合
List hash2 = stringRedisTemplate.opsForHash().values("hash");

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

Spring boot多數(shù)據(jù)源配置,配置一個(gè)1號(hào)庫(kù),一個(gè)4號(hào)庫(kù)

添加依賴


    org.apache.commons
    commons-pool2


    org.springframework.boot
    spring-boot-starter-data-redis

修改application.properties配置文件

#1號(hào)庫(kù)
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號(hào)庫(kù)
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

創(chuàng)建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實(shí)現(xiàn)事務(wù)
stringRedisTemplate.setEnableTransactionSupport(true);
    try {
        stringRedisTemplate.multi();//開(kāi)啟事務(wù)
        stringRedisTemplate.opsForValue().increment("count", 1);
        stringRedisTemplate.opsForValue().increment("count1", 2);
        //提交
        stringRedisTemplate.exec();
    }catch (Exception e){
        log.error(e.getMessage(), e);
        //開(kāi)啟回滾
        stringRedisTemplate.discard();
    }

注意:StringRedisTemplate開(kāi)啟事務(wù)之后,不釋放連接。如果我們使用Spring事務(wù)管理不存在這個(gè)問(wèn)題

StringRedisTemplate實(shí)現(xiàn)樂(lè)觀鎖
redisTemplate.watch("key"); // 1
redisTemplate.multi();
redisTemplate.boundValueOps("key").set(""+id);
List list= redisTemplate.exec();
System.out.println(list);
if(list != null ){
    //操作成功
    System.out.println(id+"操作成功");
}else{
    //操作失敗
    System.out.println(id+"操作失敗");
}

StringRedisTemplate實(shí)現(xiàn)pipe管道
StringRedisTemplate實(shí)現(xiàn)分布式鎖
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緩存擊穿、穿透和雪崩
緩存擊穿,是指一個(gè)key非常熱點(diǎn),在不停的扛著大并發(fā),大并發(fā)集中對(duì)這一個(gè)點(diǎn)進(jìn)
行訪問(wèn),當(dāng)這個(gè)key在失效的瞬間,持續(xù)的大并發(fā)就穿破緩存,直接請(qǐng)求數(shù)據(jù)庫(kù),就
像在一個(gè)屏障上鑿開(kāi)了一個(gè)洞
      
緩存穿透,是指查詢一個(gè)數(shù)據(jù)庫(kù)一定不存在的數(shù)據(jù)。正常的使用緩存流程大致是,
數(shù)據(jù)查詢先進(jìn)行緩存查詢,如果key不存在或者key已經(jīng)過(guò)期,再對(duì)數(shù)據(jù)庫(kù)進(jìn)行查
詢,并把查詢到的對(duì)象,放進(jìn)緩存。如果數(shù)據(jù)庫(kù)查詢對(duì)象為空,則不放進(jìn)緩存。
解決辦法是即使查出的對(duì)象為空,也放入緩存時(shí)間設(shè)短一點(diǎn)。

緩存雪崩,是指在某一個(gè)時(shí)間段,緩存集中過(guò)期失效。

有問(wèn)題,請(qǐng)留言!

個(gè)人博客地址 王開(kāi)金的博客

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/75766.html

相關(guān)文章

  • Redis詳解 - SpringBoot整合Redis,RedisTemplate和注解兩種方式的使

    摘要:和注解的方法返回值要一致刪除緩存在需要?jiǎng)h除緩存的方法上加注解,執(zhí)行完這個(gè)方法之后會(huì)將中對(duì)應(yīng)的記錄刪除。代表返回值,意思是當(dāng)返回碼不等于時(shí)不緩存,也就是等于時(shí)才緩存。返回值特定值如果被設(shè)置了如果沒(méi)有被設(shè)置例子自動(dòng)將對(duì)應(yīng)到并且返回原來(lái)對(duì)應(yīng)的。 本文主要講 Redis 的使用,如何與 SpringBoot 項(xiàng)目整合,如何使用注解方式和 RedisTemplate 方式實(shí)現(xiàn)緩存。最后會(huì)給一個(gè)用...

    SexySix 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<