日B视频 亚洲,啪啪啪网站一区二区,91色情精品久久,日日噜狠狠色综合久,超碰人妻少妇97在线,999青青视频,亚洲一区二卡,让本一区二区视频,日韩网站推荐

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內不再提示

Springboot+redis操作多種實現(xiàn)

Android編程精選 ? 來源:CSDN技術社區(qū) ? 作者:Tonels ? 2021-09-22 10:48 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

一、Jedis,Redisson,Lettuce三者的區(qū)別共同點:都提供了基于Redis操作的Java API,只是封裝程度,具體實現(xiàn)稍有不同。

不同點:

1.1、Jedis

是Redis的Java實現(xiàn)的客戶端。支持基本的數(shù)據(jù)類型如:String、Hash、List、Set、Sorted Set。

特點:使用阻塞的I/O,方法調用同步,程序流需要等到socket處理完I/O才能執(zhí)行,不支持異步操作。Jedis客戶端實例不是線程安全的,需要通過連接池來使用Jedis。

1.2、Redisson

優(yōu)點點:分布式鎖,分布式集合,可通過Redis支持延遲隊列。

1.3、 Lettuce

用于線程安全同步,異步和響應使用,支持集群,Sentinel,管道和編碼器

基于Netty框架的事件驅動的通信層,其方法調用是異步的。Lettuce的API是線程安全的,所以可以操作單個Lettuce連接來完成各種操作。

二、RedisTemplate2.1、使用配置

maven配置引入,(要加上版本號,我這里是因為Parent已聲明)


	

<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> dependency>

application-dev.yml


	

spring: redis: host:192.168.1.140 port:6379 password: database:15#指定redis的分庫(共16個0到15)

2.2、使用示例


	

@Resource privateStringRedisTemplatestringRedisTemplate; @Override publicCustomersEntityfindById(Integerid){ //需要緩存 //所有涉及的緩存都需要刪除,或者更新 try{ StringtoString=stringRedisTemplate.opsForHash().get(REDIS_CUSTOMERS_ONE,id+"").toString(); if(toString!=null){ returnJSONUtil.toBean(toString,CustomersEntity.class); } }catch(Exceptione){ e.printStackTrace(); } //緩存為空的時候,先查,然后緩存redis OptionalbyId=customerRepo.findById(id); if(byId.isPresent()){ CustomersEntitycustomersEntity=byId.get(); try{ stringRedisTemplate.opsForHash().put(REDIS_CUSTOMERS_ONE,id+"",JSONUtil.toJsonStr(customersEntity)); }catch(Exceptione){ e.printStackTrace(); } returncustomersEntity; } returnnull; }

2.3、擴展

2.3.1、spring-boot-starter-data-redis的依賴包

3.3.2、stringRedisTemplate API(部分展示)

opsForHash --》 hash操作

opsForList --》 list操作

opsForSet --》 set操作

opsForValue --》 string操作

opsForZSet --》 Zset操作

3.3.3 StringRedisTemplate默認序列化機制


	

publicclassStringRedisTemplateextendsRedisTemplate<String,String>{ /** *ConstructsanewStringRedisTemplateinstance.{@link#setConnectionFactory(RedisConnectionFactory)} *and{@link#afterPropertiesSet()}stillneedtobecalled. */ publicStringRedisTemplate(){ RedisSerializerstringSerializer=newStringRedisSerializer(); setKeySerializer(stringSerializer); setValueSerializer(stringSerializer); setHashKeySerializer(stringSerializer); setHashValueSerializer(stringSerializer); } }

三、RedissonClient 操作示例

3.1 基本配置

3.1.1、Maven pom 引入

	

<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> dependency> <dependency> <groupId>org.redissongroupId> <artifactId>redissonartifactId> <version>3.8.2version> <optional>trueoptional> dependency> <dependency> <groupId>org.redissongroupId> <artifactId>redisson-spring-boot-starterartifactId> <version>LATESTversion> dependency>

3.1.2、添加配置文件Yaml或者json格式

redisson-config.yml


	

#Redisson配置 singleServerConfig: address:"redis://192.168.1.140:6379" password:null clientName:null database:15#選擇使用哪個數(shù)據(jù)庫0~15 idleConnectionTimeout:10000 pingTimeout:1000 connectTimeout:10000 timeout:3000 retryAttempts:3 retryInterval:1500 reconnectionTimeout:3000 failedAttempts:3 subscriptionsPerConnection:5 subscriptionConnectionMinimumIdleSize:1 subscriptionConnectionPoolSize:50 connectionMinimumIdleSize:32 connectionPoolSize:64 dnsMonitoringInterval:5000 #dnsMonitoring:false threads:0 nettyThreads:0 codec: class:"org.redisson.codec.JsonJacksonCodec" transportMode:"NIO"

或者,配置 redisson-config.json


	

{ "singleServerConfig":{ "idleConnectionTimeout":10000, "pingTimeout":1000, "connectTimeout":10000, "timeout":3000, "retryAttempts":3, "retryInterval":1500, "reconnectionTimeout":3000, "failedAttempts":3, "password":null, "subscriptionsPerConnection":5, "clientName":null, "address":"redis://192.168.1.140:6379", "subscriptionConnectionMinimumIdleSize":1, "subscriptionConnectionPoolSize":50, "connectionMinimumIdleSize":10, "connectionPoolSize":64, "database":0, "dnsMonitoring":false, "dnsMonitoringInterval":5000 }, "threads":0, "nettyThreads":0, "codec":null, "useLinuxNativeEpoll":false }

3.1.3、讀取配置

新建讀取配置類


	

@Configuration publicclassRedissonConfig{ @Bean publicRedissonClientredisson()throwsIOException{ //兩種讀取方式,Config.fromYAML和Config.fromJSON //Configconfig=Config.fromJSON(RedissonConfig.class.getClassLoader().getResource("redisson-config.json")); Configconfig=Config.fromYAML(RedissonConfig.class.getClassLoader().getResource("redisson-config.yml")); returnRedisson.create(config); } }

或者,在 application.yml中配置如下


	

spring: redis: redisson: config:classpath:redisson-config.yaml

3.2 使用示例


	

@RestController @RequestMapping("/") publicclassTeController{ @Autowired privateRedissonClientredissonClient; staticlongi=20; staticlongsum=300; //==========================String======================= @GetMapping("/set/{key}") publicStrings1(@PathVariableStringkey){ //設置字符串 RBucketkeyObj=redissonClient.getBucket(key); keyObj.set(key+"1-v1"); returnkey; } @GetMapping("/get/{key}") publicStringg1(@PathVariableStringkey){ //設置字符串 RBucketkeyObj=redissonClient.getBucket(key); Strings=keyObj.get(); returns; } //==========================hash=======================-= @GetMapping("/hset/{key}") publicStringh1(@PathVariableStringkey){ Urur=newUr(); ur.setId(MathUtil.randomLong(1,20)); ur.setName(key); //存放Hash RMapss=redissonClient.getMap("UR"); ss.put(ur.getId().toString(),ur); returnur.toString(); } @GetMapping("/hget/{id}") publicStringh2(@PathVariableStringid){ //hash查詢 RMapss=redissonClient.getMap("UR"); Urur=ss.get(id); returnur.toString(); } //查詢所有的keys @GetMapping("/all") publicStringall(){ RKeyskeys=redissonClient.getKeys(); Iterablekeys1=keys.getKeys(); keys1.forEach(System.out::println); returnkeys.toString(); } //================================讀寫鎖測試============================= @GetMapping("/rw/set/{key}") publicvoidrw_set(){ //RedissonLock. RBucketls_count=redissonClient.getBucket("LS_COUNT"); ls_count.set("300",360000000l,TimeUnit.SECONDS); } //減法運算 @GetMapping("/jf") publicvoidjf(){ Stringkey="S_COUNT"; //RAtomicLongatomicLong=redissonClient.getAtomicLong(key); //atomicLong.set(sum); //longl=atomicLong.decrementAndGet(); //System.out.println(l); RAtomicLongatomicLong=redissonClient.getAtomicLong(key); if(!atomicLong.isExists()){ atomicLong.set(300l); } while(i==0){ if(atomicLong.get()>0){ longl=atomicLong.getAndDecrement(); try{ Thread.sleep(1000l); }catch(InterruptedExceptione){ e.printStackTrace(); } i--; System.out.println(Thread.currentThread().getName()+"->"+i+"->"+l); } } } @GetMapping("/rw/get") publicStringrw_get(){ Stringkey="S_COUNT"; Runnabler=newRunnable(){ @Override publicvoidrun(){ RAtomicLongatomicLong=redissonClient.getAtomicLong(key); if(!atomicLong.isExists()){ atomicLong.set(300l); } if(atomicLong.get()>0){ longl=atomicLong.getAndDecrement(); i--; System.out.println(Thread.currentThread().getName()+"->"+i+"->"+l); } } }; while(i!=0){ newThread(r).start(); //newThread(r).run(); //newThread(r).run(); //newThread(r).run(); //newThread(r).run(); } RBucketbucket=redissonClient.getBucket(key); Strings=bucket.get(); System.out.println("================線程已結束================================"+s); returns; } }

4.3 擴展

4.3.1 豐富的jar支持,尤其是對 Netty NIO框架

4.3.2 豐富的配置機制選擇,這里是詳細的配置說明

https://github.com/redisson/redisson/wiki/2.-Configuration

關于序列化機制中,就有很多

ebfcba9a-1668-11ec-8fb8-12bb97331649.pngec0676fc-1668-11ec-8fb8-12bb97331649.png

4.3.3 API支持(部分展示),具體的 Redis --> RedissonClient ,可查看這里

https://github.com/redisson/redisson/wiki/11.-Redis-commands-mapping

ec127c54-1668-11ec-8fb8-12bb97331649.png


4.3.4 輕便的豐富的鎖機制的實現(xiàn)

Lock

Fair Lock

MultiLock

RedLock

ReadWriteLock

Semaphore

PermitExpirableSemaphore

CountDownLatch

四、基于注解實現(xiàn)的Redis緩存4.1 Maven 和 YML配置

參考 RedisTemplate 配置。另外,還需要額外的配置類


	

//todo定義序列化,解決亂碼問題 @EnableCaching @Configuration @ConfigurationProperties(prefix="spring.cache.redis") publicclassRedisCacheConfig{ privateDurationtimeToLive=Duration.ZERO; publicvoidsetTimeToLive(DurationtimeToLive){ this.timeToLive=timeToLive; } @Bean publicCacheManagercacheManager(RedisConnectionFactoryfactory){ RedisSerializerredisSerializer=newStringRedisSerializer(); Jackson2JsonRedisSerializerjackson2JsonRedisSerializer=newJackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉換異常的問題 ObjectMapperom=newObjectMapper(); om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //配置序列化(解決亂碼的問題) RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig() .entryTtl(timeToLive) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManagercacheManager=RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); returncacheManager; } }

4.2 使用示例


	

@Transactional @Service publicclassReImplimplementsRedisService{ @Resource privateCustomerRepocustomerRepo; @Resource privateStringRedisTemplatestringRedisTemplate; publicstaticfinalStringREDIS_CUSTOMERS_ONE="Customers"; publicstaticfinalStringREDIS_CUSTOMERS_ALL="allList"; //=====================================================================使用Springcahce注解方式實現(xiàn)緩存 //==================================單個操作 @Override @Cacheable(value="cache:customer",unless="null==#result",key="#id") publicCustomersEntitycacheOne(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } @Override @Cacheable(value="cache:customer",unless="null==#result",key="#id") publicCustomersEntitycacheOne2(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } //todo自定義redis緩存的key, @Override @Cacheable(value="cache:customer",unless="null==#result",key="#root.methodName+'.'+#id") publicCustomersEntitycacheOne3(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.isPresent()?byId.get():null; } //todo這里緩存到redis,還有響應頁面是String(加了很多轉義符,),不是Json格式 @Override @Cacheable(value="cache:customer",unless="null==#result",key="#root.methodName+'.'+#id") publicStringcacheOne4(Integerid){ finalOptionalbyId=customerRepo.findById(id); returnbyId.map(JSONUtil::toJsonStr).orElse(null); } //todo緩存json,不亂碼已處理好,調整序列化和反序列化 @Override @Cacheable(value="cache:customer",unless="null==#result",key="#root.methodName+'.'+#id") publicCustomersEntitycacheOne5(Integerid){ OptionalbyId=customerRepo.findById(id); returnbyId.filter(obj->!StrUtil.isBlankIfStr(obj)).orElse(null); } //==================================刪除緩存 @Override @CacheEvict(value="cache:customer",key="'cacheOne5'+'.'+#id") publicObjectdel(Integerid){ //刪除緩存后的邏輯 returnnull; } @Override @CacheEvict(value="cache:customer",allEntries=true) publicvoiddel(){ } @CacheEvict(value="cache:all",allEntries=true) publicvoiddelall(){ } //==================List操作 @Override @Cacheable(value="cache:all") publicListcacheList(){ Listall=customerRepo.findAll(); returnall; } //todo先查詢緩存,再校驗是否一致,然后更新操作,比較實用,要清楚緩存的數(shù)據(jù)格式(明確業(yè)務和緩存模型數(shù)據(jù)) @Override @CachePut(value="cache:all",unless="null==#result",key="#root.methodName") publicListcacheList2(){ Listall=customerRepo.findAll(); returnall; } }

4.3 擴展

基于spring緩存實現(xiàn)

來源:blog.csdn.net/qq_42105629/article/details/102589319

編輯:jq

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • spring
    +關注

    關注

    0

    文章

    341

    瀏覽量

    16060
  • Boot
    +關注

    關注

    0

    文章

    154

    瀏覽量

    37925
  • Redis
    +關注

    關注

    0

    文章

    394

    瀏覽量

    12258
  • SpringBoot
    +關注

    關注

    0

    文章

    178

    瀏覽量

    718

原文標題:Spring Boot 操作 Redis 的各種實現(xiàn)

文章出處:【微信號:AndroidPush,微信公眾號:Android編程精選】歡迎添加關注!文章轉載請注明出處。

收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關推薦
    熱點推薦

    Redis應用監(jiān)控指標大盤點

    Redis作為高性能內存數(shù)據(jù)庫,廣泛應用于緩存、會話存儲、消息隊列等場景。對Redis運行狀況的有效監(jiān)控,是保障業(yè)務穩(wěn)定性的關鍵。本文的目的是幫助運維工程師建立完整的Redis監(jiān)控知識體系,講解需要監(jiān)控哪些指標、如何采集這些指標
    的頭像 發(fā)表于 04-09 10:07 ?185次閱讀

    全方位對比:Redis能取代MySQL嗎?看完這篇你就懂了

    Redis能不能取代MySQL?答案很明確:不能取代,但可以互補。
    的頭像 發(fā)表于 04-07 10:50 ?211次閱讀
    全方位對比:<b class='flag-5'>Redis</b>能取代MySQL嗎?看完這篇你就懂了

    Redis哨兵模式的自動故障檢測與主從切換實戰(zhàn)

    Redis 主從復制解決了讀擴展和數(shù)據(jù)冗余問題,但主節(jié)點故障時需要人工介入切換,這在生產環(huán)境中是不可接受的。Sentinel(哨兵)模式在主從架構之上增加了自動故障檢測和故障轉移能力,是 Redis 高可用的標準方案之一。
    的頭像 發(fā)表于 02-27 11:05 ?321次閱讀

    Redis內存管理、持久化策略與慢查詢排查分析

    Redis 在生產環(huán)境中承擔著緩存、會話存儲、消息隊列、分布式鎖等多種角色。隨著數(shù)據(jù)量增長和并發(fā)壓力上升,內存碎片、持久化 I/O 抖動、慢查詢堆積這三類問題會逐漸顯現(xiàn),直接影響服務延遲和穩(wěn)定性。Redis 8.x 在內存管理和
    的頭像 發(fā)表于 02-27 11:00 ?321次閱讀

    【產品應用】儲能網關EM-1000與EM-1000G的Redis性能對比

    視頻推薦隨著儲能控制系統(tǒng)智能化發(fā)展,對實時處理和高速緩存需求提升。本測試對EM-1000與EM-1000G的Redis性能進行對比,評估其在吞吐、響應與穩(wěn)定性上的差異,為客戶提供精準硬件選型依據(jù)
    的頭像 發(fā)表于 12-02 11:39 ?501次閱讀
    【產品應用】儲能網關EM-1000與EM-1000G的<b class='flag-5'>Redis</b>性能對比

    如何使用SpringBoot、Vue2.0、MySQL開發(fā)一套云診所系統(tǒng)?

    (RESTful)等。 對于云診所系統(tǒng),SpringBoot可以用于實現(xiàn)患者管理、預約掛號、電子病歷、藥品管理、收費管理等核心功能。 前端:V
    的頭像 發(fā)表于 11-27 16:02 ?419次閱讀
    如何使用<b class='flag-5'>SpringBoot</b>、Vue2.0、MySQL開發(fā)一套云診所系統(tǒng)?

    醫(yī)院隨訪管理系統(tǒng)源碼,三級隨訪系統(tǒng)源碼,Java+Springboot,Vue,Ant-Design+MySQL5

    Java版隨訪系統(tǒng)源碼,醫(yī)院隨訪管理系統(tǒng)源碼,三級隨訪系統(tǒng)源碼,B/S前后端分離架構,自主版權,落地案例。 技術框架:Java+Springboot,Vue,Ant-Design+MySQL5 開發(fā)
    的頭像 發(fā)表于 11-08 14:48 ?753次閱讀
    醫(yī)院隨訪管理系統(tǒng)源碼,三級隨訪系統(tǒng)源碼,Java+<b class='flag-5'>Springboot</b>,Vue,Ant-Design+MySQL5

    深度剖析Redis的兩大持久化機制

    凌晨3點,我被一通緊急電話驚醒。線上Redis集群崩潰,6GB的緩存數(shù)據(jù)全部丟失,導致MySQL瞬間承壓暴增,整個交易系統(tǒng)陷入癱瘓。事后復盤發(fā)現(xiàn),問題的根源竟是一個被忽視的持久化配置細節(jié)。
    的頭像 發(fā)表于 09-17 16:22 ?727次閱讀

    Redis Sentinel和Cluster模式如何選擇

    在我十年的運維生涯中,見過太多團隊在Redis集群方案選擇上踩坑。有的團隊盲目追求"高大上"的Cluster模式,結果運維復雜度爆表;有的團隊死守Sentinel不放,最后擴展性成了瓶頸。今天,我想通過這篇萬字長文,把我在生產環(huán)境中積累的經驗全部分享給你。
    的頭像 發(fā)表于 09-08 09:31 ?786次閱讀

    Redis集群部署配置詳解

    Redis集群是一種分布式Redis解決方案,通過數(shù)據(jù)分片和主從復制實現(xiàn)高可用性和橫向擴展。集群將整個數(shù)據(jù)集分割成16384個哈希槽(hash slots),每個節(jié)點負責一部分槽位。
    的頭像 發(fā)表于 07-17 11:04 ?1201次閱讀

    Redis集群部署與性能優(yōu)化實戰(zhàn)

    Redis作為高性能的內存數(shù)據(jù)庫,在現(xiàn)代互聯(lián)網架構中扮演著關鍵角色。作為運維工程師,掌握Redis的部署、配置和優(yōu)化技能至關重要。本文將從實戰(zhàn)角度出發(fā),詳細介紹Redis集群的搭建、性能優(yōu)化以及監(jiān)控運維的核心技術。
    的頭像 發(fā)表于 07-08 17:56 ?1046次閱讀

    【經驗分享】在Omni3576上編譯Redis-8.0.2源碼,并安裝及性能測試

    本文首先介紹Redis是什么,然后介紹如何在Omni3576上編譯Redis-8.0.2源碼,以及從源碼編譯、安裝Redis,最后介紹如何在Omni3576上運行Redis性能測試,并
    的頭像 發(fā)表于 06-05 08:05 ?1112次閱讀
    【經驗分享】在Omni3576上編譯<b class='flag-5'>Redis</b>-8.0.2源碼,并安裝及性能測試

    【幸狐Omni3576邊緣計算套件試用體驗】Redis最新8.0.2版本源碼安裝及性能測試

    命令行程序,用于操作Redis服務中的數(shù)據(jù); 2.4 安裝Redis 使用如下命令將Redis可執(zhí)行程序安裝到系統(tǒng)目錄: sudo make install 命令輸出如下: 可以看
    發(fā)表于 06-03 01:28

    在cypress 3014進行多種分辨率刷新率切換的操作,是否可行?

    我想在cypress 3014進行多種分辨率刷新率切換的操作,不知道是否可行,有無相關demo或者說明文檔可提供
    發(fā)表于 05-09 08:25

    Redis 再次開源!

    “ ?Redis 現(xiàn)已采用 AGPLv3 開源許可證。? ” Redis CEO 的 Blog 以下是 Redis CEO Rowan Trollope 的 Blog: 像 AWS 和 GCP 這樣
    的頭像 發(fā)表于 05-06 18:26 ?1075次閱讀
    石屏县| 大洼县| 驻马店市| 泰和县| 威信县| 金乡县| 堆龙德庆县| 轮台县| 崇文区| 定日县| 蒙山县| 崇信县| 梅州市| 汝州市| 赣州市| 乌兰察布市| 左贡县| 鄢陵县| 班戈县| 福建省| 乳山市| 沅陵县| 澄迈县| 城步| 南皮县| 论坛| 林周县| 隆尧县| 靖宇县| 军事| 阳谷县| 习水县| 和顺县| 桐柏县| 锡林浩特市| 运城市| 阳高县| 丘北县| 北安市| 新化县| 思南县|