最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用StringRedisTemplate操作Redis方法詳解

 更新時間:2023年08月01日 09:51:24   作者:wotrd  
這篇文章主要為大家介紹了使用StringRedisTemplate操作Redis方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

Redis簡介

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

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

Springboot的redis單數(shù)據(jù)源配置特別簡單

(1)配置appliation.properties文件

spring.redis.host=x.x.x.x
spring.redis.port=6379
#redis的數(shù)據(jù)庫號
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數(shù)據(jù)
ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
valueOperations.set("strRedis","StringRedisTemplate");
valueOperations.get("strRedis"); 
#設置過期時間     
set("timeStep", new Date().getTime()+"", 2 ,TimeUnit.MINUTES);
#獲取SetOperations操作Set數(shù)據(jù)
 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數(shù)據(jù),list可以用來實現(xiàn)隊列。
 //將數(shù)據(jù)添加到key對應的現(xiàn)有數(shù)據(jù)的左邊
 Long redisList = stringRedisTemplate.opsForList().leftPush("redisList", "3");
 stringRedisTemplate.opsForList().leftPush("redisList", "4");
 //將數(shù)據(jù)添加到key對應的現(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<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(可變參數(shù))
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");  
#數(shù)字加x
Long count = stringRedisTemplate.boundValueOps("count").increment(1);//val +1 
#獲取過期時間,不設的話為-1
Long time = stringRedisTemplate.getExpire("count")

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

配置一個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

創(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實現(xiàn)事務

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實現(xiàn)樂觀鎖

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實現(xiàn)pipe管道

StringRedisTemplate實現(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緩存擊穿、穿透和雪崩

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

以上就是使用StringRedisTemplate操作Redis方法詳解的詳細內(nèi)容,更多關于StringRedisTemplate操作Redis的資料請關注腳本之家其它相關文章!

相關文章

  • SpringBoot的監(jiān)控(Actuator)功能用法詳解

    SpringBoot的監(jiān)控(Actuator)功能用法詳解

    這篇文章主要介紹了SpringBoot的監(jiān)控(Actuator)功能用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • MyBatis Plus中InnerInterceptor的實現(xiàn)

    MyBatis Plus中InnerInterceptor的實現(xiàn)

    本文主要介紹了MyBatis Plus中InnerInterceptor的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-03-03
  • 解決JSONObject.toJSONString()輸出null的問題

    解決JSONObject.toJSONString()輸出null的問題

    這篇文章主要介紹了解決JSONObject.toJSONString()輸出null的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • MyBatisPlus分頁插件IPage用法實現(xiàn)

    MyBatisPlus分頁插件IPage用法實現(xiàn)

    本文主要介紹了MyBatisPlus分頁插件IPage用法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2025-06-06
  • Java實現(xiàn)PDF文件的分割與加密功能

    Java實現(xiàn)PDF文件的分割與加密功能

    這篇文章主要為大家分享了如何利用Java語言實現(xiàn)PDF文件的分割與加密以及封面圖的生成,文中的示例代碼簡潔易懂,感興趣的可以了解一下
    2022-04-04
  • JavaOOP封裝實例解讀

    JavaOOP封裝實例解讀

    封裝通過private限制屬性訪問,提供get/set方法控制數(shù)據(jù)讀寫,確保值合法,示例中Student類屬性私有,Test類需調(diào)用set方法賦值并驗證,get方法獲取值,實現(xiàn)數(shù)據(jù)隱藏與安全操作
    2025-09-09
  • 系統(tǒng)運維問題排查-java內(nèi)存過高分析及說明

    系統(tǒng)運維問題排查-java內(nèi)存過高分析及說明

    本文總結了監(jiān)控Java進程內(nèi)存與線程狀態(tài)的常用命令及參數(shù),包括top排序、jmap查看內(nèi)存分布、jstat分析GC數(shù)據(jù)、jstack解析線程狀態(tài)等,強調(diào)需使用與進程一致的用戶執(zhí)行,并解析了線程狀態(tài)和內(nèi)存區(qū)域的含義
    2025-07-07
  • spring boot中各個版本的redis配置問題詳析

    spring boot中各個版本的redis配置問題詳析

    這篇文章主要給大家介紹了關于spring boot中各個版本的redis配置問題的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-12-12
  • IDEA快速創(chuàng)建SpringBoot項目的圖文詳解與避坑指南

    IDEA快速創(chuàng)建SpringBoot項目的圖文詳解與避坑指南

    IntelliJ IDEA作為Java開發(fā)者的?首選IDE?,深度集成Spring Boot支持,可一鍵生成項目骨架和智能配置依賴,下面我們就來看看如何零基礎?通過IDEA創(chuàng)建Spring Boot項目吧
    2025-05-05
  • IDEA+Maven打JAR包的兩種方法步驟詳解

    IDEA+Maven打JAR包的兩種方法步驟詳解

    Idea中為一般的非Web項目打Jar包是有自己的方法的,下面這篇文章主要給大家介紹了關于IDEA+Maven打JAR包的兩種方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-09-09

最新評論

禄丰县| 平顺县| 城市| 庆元县| 电白县| 梅州市| 措勤县| 龙里县| 鹤山市| 上虞市| 甘南县| 凤山市| 深州市| 左贡县| 元谋县| 汤阴县| 鄂伦春自治旗| 铜鼓县| 平定县| 宁强县| 汉川市| 扎赉特旗| 堆龙德庆县| 江城| 宜宾市| 珲春市| 巴彦淖尔市| 隆尧县| 双峰县| 南开区| 莒南县| 德格县| 科技| 黑龙江省| 阆中市| 石屏县| 台南市| 东丰县| 苏尼特左旗| 隆化县| 屯门区|