Redisson教程

  • Redisson入門

    Author:Ricky  Date:2017-04-24node

  • Redisson概述

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

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

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

適用場景

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

案例

  百度、NetFlix等都在使用。數據庫

  • Redisson功能

  • Redisson功能

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

引入依賴包 json

<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實現分佈式的最佳選擇。

相關文章
相關標籤/搜索