Redisson教程


  • Redisson入門

    Author:Ricky  Date:2017-04-24

  • Redisson概述

      Redisson是架設在Redis基礎上的一個Java駐內存數據網格(In-Memory Data Grid)。充分的利用了Redis鍵值數據庫提供的一系列優勢,基於Java實用工具包中常用接口,為使用者提供了一系列具有分布式特性的常用工具類。使得原本作為協調單機多線程並發程序的工具包獲得了協調分布式多機多線程並發系統的能力,大大降低了設計和研發大規模分布式系統的難度。同時結合各富特色的分布式服務,更進一步簡化了分布式環境中程序相互之間的協作。

  Redisson始於2013年12月22日,至今已有三年多的發展,日趨成熟。

  地址:https://github.com/redisson/redisson

適用場景

  分布式應用,分布式緩存,分布式回話管理,分布式服務(任務,延遲任務,執行器),分布式redis客戶端

案例

  百度、NetFlix等都在使用。

  • Redisson功能

  • Redisson功能

    • 支持同步/異步/異步流/管道流方式連接
    • 多樣化數據序列化
    • 集合數據分片
    • 分布式對象
    • 分布式集合
    • 分布式鎖和同步器
    • 分布式服務
    • 獨立節點模式
    • 三方框架整合
  • HelloWorld 

引入依賴包

<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson</artifactId>
  <version>3.3.2</version>
</dependency>

程序化配置方法

         Config config = new Config();

         config. useSingleServer().setAddress("127.0.0.1:6379");

         RedissonClient redisson = Redisson.create(config);

文件方式配置

         Config config = Config.fromJSON(new File("config-file.json"));

         Config config = Config.fromYAML(new File("config-file.yaml")); RedissonClient RedissonClient  redisson = Redisson.create(config);

Spring方式

         <redisson:client>

                   <redisson:single-server address=“127.0.0.1:6379" />

         </redisson:client>

HelloWorld 3

驗證是否成功

         redisson.getConfig().toJSON().toString()

結果 {"singleServerConfig":{"idleConnectionTimeout":10000,"pingTimeout":1000,"connectTimeout":10000,"timeout":3000,"retryAttempts":3,"retryInterval":1500,"reconnectionTimeout":3000,"failedAttempts":3,"subscriptionsPerConnection":5,"address":"redis://127.0.0.1:6379","subscriptionConnectionMinimumIdleSize":1,"subscriptionConnectionPoolSize":50,"connectionMinimumIdleSize":10,"connectionPoolSize":64,"database":0,"dnsMonitoring":false,"dnsMonitoringInterval":5000},"threads":0,"nettyThreads":0,"codec":{"class":"org.redisson.codec.JsonJacksonCodec"},"codecProvider":{"class":"org.redisson.codec.DefaultCodecProvider"},"resolverProvider":{"class":"org.redisson.liveobject.provider.DefaultResolverProvider"},"redissonReferenceEnabled":true,"useLinuxNativeEpoll":false}

連接方式

         RedissonClient client = Redisson.create(config);

        RAtomicLong longObject = client.getAtomicLong('myLong');

         // 同步執行方式

          longObject.compareAndSet(3, 401);

         // 異步執行方式

          longObject.compareAndSetAsync(3, 401);

          RedissonReactiveClient client = Redisson.createReactive(config); RAtomicLongReactive longObject = client.getAtomicLong('myLong');

         // 異步流執行方式

         longObject.compareAndSet(3, 401);

數據序列化

  

集合數據分片

在集群模式下,Redisson為單個Redis集合類型提供了自動分片的功能。

在自動分片功能的幫助下,單個集合拆分以后均勻的分布在整個集群里,而不是被擠在單一一個節點里。

Redisson通過自身的分片算法,將一個大集合拆分為若干個片段(默認231個,分片數量范圍是3 - 16834),然后將拆分后的片段均勻的分布到集群里各個節點里,保證每個節點分配到的片段數量大體相同。比如在默認情況下231個片段分到含有4個主節點的集群里,每個主節點將會分配到大約57個片段,同樣的道理如果有5個主節點,每個節點會分配到大約46個片段。

目前支持的數據結構類型包括SetMap.

分布式對象

通用對象桶(Object Bucket

二進制流(Binary Stream

地理空間對象桶(Geospatial Bucket

 BitSet

原子整長形(AtomicLong

原子雙精度浮點數(AtomicDouble

話題(訂閱分發)

布隆過濾器(Bloom Filter

基數估計算法(HyperLogLog

示例

         通用桶對象

         RBucket<AnyObject> bucket = redisson.getBucket("anyObject"); bucket.set(new AnyObject(1));

         AnyObject obj = bucket.get();

         原子整長型

         RAtomicLong atomicLong = redisson.getAtomicLong("myAtomicLong"); atomicLong.set(3);

         atomicLong.incrementAndGet();

         atomicLong.get();

分布式集合

映射(Map

多值映射(Multimap

集(Set

有序集(SortedSet

計分排序集(ScoredSortedSet

字典排序集(LexSortedSet

列表(List

列隊(Queue

雙端隊列(Deque

阻塞隊列(Blocking Queue

有界阻塞列隊(Bounded Blocking Queue

 阻塞雙端列隊(Blocking Deque

阻塞公平列隊(Blocking Fair Queue

延遲列隊(Delayed Queue

 優先隊列(Priority Queue

優先雙端隊列(Priority Deque

分布式集合

示例

         Map

         RMap<String, SomeObject> map = redisson.getMap("anyMap");

         SomeObject prevObject = map.put("123", new SomeObject());

          SomeObject currentObject = map.putIfAbsent("323", new SomeObject());

         SomeObject obj = map.remove("123");

         Set

         RSet<SomeObject> set = redisson.getSet("anySet");

         set.add(new SomeObject());

         set.remove(new SomeObject());

分布式鎖

可重入鎖(Reentrant Lock

公平鎖(Fair Lock

聯鎖(MultiLock

紅鎖(RedLock

讀寫鎖(ReadWriteLock

信號量(Semaphore

可過期性信號量(PermitExpirableSemaphore

閉鎖(CountDownLatch

示例

         RLock lock = redisson.getLock("anyLock");

         // 最常見的使用方法

          lock.lock();

         // 支持過期解鎖功能 10秒鍾以后自動解鎖

          // 無需調用unlock方法手動解鎖

         lock.lock(10, TimeUnit.SECONDS);

         // 嘗試加鎖,最多等待100秒,上鎖以后10秒自動解鎖 boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); lock.unlock();

分布式服務

分布式遠程服務(Remote Service

分布式實時對象(Live Object)服務

分布式執行服務(Executor Service

分布式調度任務服務(Scheduler Service

分布式映射歸納服務(MapReduce

 

服務端(遠端)實例

RRemoteService remoteService = redisson.getRemoteService();

SomeServiceImpl someServiceImpl = new SomeServiceImpl();

 // 在調用遠程方法以前,應該首先注冊遠程服務

 // 只注冊了一個服務端工作者實例,只能同時執行一個並發調用

remoteService.register(SomeServiceInterface.class, someServiceImpl);

 // 注冊了12個服務端工作者實例,可以同時執行12個並發調用

remoteService.register(SomeServiceInterface.class, someServiceImpl, 12);

客戶端(本地)實例

         RRemoteService remoteService = redisson.getRemoteService();

         SomeServiceInterface service = remoteService.get(SomeServiceInterface.class);

         String result = service.doSomeStuff(1L, "secondParam", new AnyParam());

獨立節點模式

Redisson Node指的是Redisson在分布式運算環境中作為獨立節點運行的一種模式。Redisson Node的功能可以用來執行通過分布式執行服務分布式調度執行服務發送的遠程任務,也可以用來為分布式遠程服務提供遠端服務。

依賴redisson-all.jar

獨立節點模式-配置

// Redisson程序化配置代碼

Config config = ...

 // Redisson Node 程序化配置方法

RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);

Map<String, Integer> workers = new HashMap<String, Integer>();

workers.put("test", 1);

nodeConfig.setExecutorServiceWorkers(workers);

// 創建一個Redisson Node實例

RedissonNode node = RedissonNode.create(nodeConfig);

// 或者通過指定的Redisson實例創建Redisson Node實例

RedissonNode node = RedissonNode.create(nodeConfig, redisson);

node.start();

node.shutdown();

三方框架整合

Spring框架整合

Spring Cache整合

Hibernate整合

 Tomcat會話管理器(Tomcat Session Manager

Spring Session會話管理器

三方框架-Spring整合

基本配置:

<redisson:client id="myRedisson"> <redisson:single-server address="127.0.0.1:6379"/> </redisson:client>

完全配置:

                   參照附件:Redisson說明文檔.pdf

    • 三方框架-Spring調用

        

         @Service
public class RedissonUtils2 implements InitializingBean {
    @Autowired
    private RedissonClient redissonClient;


    public void afterPropertiesSet() throws Exception {
        Redisson redisson= (Redisson) redissonClient;
       RAtomicDouble dd= redissonClient.getAtomicDouble("tt");
       dd.set(1.22);
        System.out.println("bean初始化后置方法"+redisson.getConfig().toJSON().toString());
    }
}

總結

                   Redisson是redis分布式方向落地的產品,不僅開源免費,而且內置分布式鎖,分布式服務等諸多功能,是基於redis實現分布式的最佳選擇。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM