使用vertx共享数据

摘要:
作者:Tim Fox方法总结了所有方法实例、方法、抽象方法、修饰符和类型方法,并解释了voidaddAndGet会自动向计数器添加一个值,然后返回一个新的计数voidcompareAndSet。只有当当前值为预期值时,才能将计数器设置为指定值。

Using Shared Data with Vert.x

io.vertx.core.shareddata

接口计数器



  • 公共接口柜台
    一个异步计数器,可用于跨集群维护一致的计数。
    作者:
    蒂姆·福克斯
    • 方法细节

      • 得到

        无效get(处理程序 < AsyncResult <  >> resultHandler)
        获取计数器的当前值
        参数:
        resultHandler -将传递值的处理程序
      • IncrementAndGet

        无效的crementAndGet 处理程序 < AsyncResult <  >> resultHandler)
        自动增加计数器并返回新计数
        参数:
        resultHandler -将传递值的处理程序
      • getAndIncrement

        void getAndIncrement(Handler < AsyncResult < Long >> resultHandler)
        以原子方式递增计数器,并在递增之前返回值。
        参数:
        resultHandler -将传递值的处理程序
      • 递减并获取

        void decrementAndGet(Handler < AsyncResult < Long >> resultHandler)
        自动减少计数器并返回新计数
        参数:
        resultHandler -将传递值的处理程序
      • addAndGet

        void addAndGet(long value,
                        Handler < AsyncResult < Long >> resultHandler)
        将值自动添加到计数器,然后返回新的计数
        参数:
        value -要添加的值
        resultHandler -将传递值的处理程序
      • getAndAdd

        void getAndAdd(long value,
                        Handler < AsyncResult < Long >> resultHandler)
        将值原子地添加到计数器,然后在添加之前返回值
        参数:
        value -要添加的值
        resultHandler -将传递值的处理程序
      • compareAndSet

        void compareAndSet(期待已久,
                           长值
                           Handler < AsyncResult < Boolean >> resultHandler)
        仅当当前值为期望值时,才将计数器设置为指定值。这是原子发生的。
        参数:
        expected -期望值
        value -新价值
        resultHandler -处理程序将在成功时传递true

使用vertx共享数据

Shared data contains functionality that allows you to safely share data between different parts of your application, or 

共享数据功能允许你安全的在不同的模块、

different applications in the same Vert.x instance or across a cluster of Vert.x instances.

或不同的应用、或不同的分布式实例之间共享数据。

Shared data includes local shared maps, distributed, cluster-wide maps, asynchronous cluster-wide locks and 

共享数据有多个方式:包括本地共享maps、分布式、宽集群的maps、异步的宽集群锁

asynchronous cluster-wide counters.

、异步的宽集群计数器。

Local shared maps

Local shared maps allow you to share data safely between different event loops (e.g. different verticles) in the same Vert.x instance.

本地共享maps允许你在不同的实例之间共享数据。

Local shared maps only allow certain data types to be used as keys and values. Those types must either be immutable, or certain other types that can be copied like Buffer. In the latter case the key/value will be copied before putting it in the map.

本地存储只允许某些数据类型被设置为keys和values,这个类型必须不可变的或某些可以被拷贝的类型例如Buffer,在最后keys/values被拷贝进map里。

This way we can ensure there is no shared access to mutable state between different threads in your Vert.x application so 

我们可以确定不会有不同线程之间有多个状态。所以

you don’t have to worry about protecting that state by synchronising access to it.

你不用担心异步访问的问题。

Here’s an example of using a shared local map:

这里有个本地共享的例子。

  1.  
    SharedData sd = vertx.sharedData();
     
     
     
    LocalMap<String, String> map1 = sd.getLocalMap("mymap1");
     
     
     
    map1.put("foo", "bar"); // Strings are immutable so no need to copyLocalMap<String, Buffer> map2 = sd.getLocalMap("mymap2");
     
     
     
    map2.put("eek", Buffer.buffer().appendInt(123)); // This buffer will be copied before adding to map// Then... in another part of your application:map1 = sd.getLocalMap("mymap1");
     
     
     
    String val = map1.get("foo");
     
     
     
    map2 = sd.getLocalMap("mymap2");
     
     
     
    Buffer buff = map2.get("eek");

Cluster-wide asynchronous maps

宽集群异步共享maps。

Cluster-wide asynchronous maps allow data to be put in the map from any node of the cluster and retrieved from any other node.

宽集群共享map允许从任何集群点、和任何节点上获取共享数据。

This makes them really useful for things like storing session state in a farm of servers hosting a Vert.x web application.

You get an instance of AsyncMap with getClusterWideMap.

这个非常有用,例如存储session状态在一个web应用的集群里。你可以获得一个AsyncMap从getClusterWideMap里。

Getting the map is asynchronous and the result is returned to you in the handler that you specify. Here’s an example:

获取map是异步返回的,你可以单独处理返回结果。

  1.  
     
  2.  
     
  3.  
    SharedData sd = vertx.sharedData();

    sd.<String, String>getClusterWideMap("mymap", res -> { if (res.succeeded()) { AsyncMap<String, String> map = res.result(); } else { // Something went wrong! } });

Putting data in a map

设置共享数据。

You put data in a map with put.

你可以用put方法设置数据。

The actual put is asynchronous and the handler is notified once it is complete:

事实上put是异步的,hander里会有通知一旦设置完成。

  1.  
    map.put("foo", "bar", resPut -> {
     
      if (resPut.succeeded()) {
     
        // Successfully put the value
     
      } else {
     
        // Something went wrong!
     
      }
     
    });

Getting data from a map

获取数据从map里。

You get data from a map with get.

你可以获取数据用get。

The actual get is asynchronous and the handler is notified with the result some time later

实际上获取也是异步的,可以在hander里获取结果。

  1.  
    map.get("foo", resGet -> {
     
      if (resGet.succeeded()) {
     
        // Successfully got the value
     
        Object val = resGet.result();
     
      } else {
     
        // Something went wrong!
     
      }
     
    });
Other map operations

map的其他操作。

You can also remove entries from an asynchronous map, clear them and get the size.

你也可以异步删除、清空map里的实例、和获取map的size。

See the API docs for more information.

查看更多。

Cluster-wide locks

宽集群的锁。

Cluster wide locks allow you to obtain exclusive locks across the cluster - this is useful when you want to do something or access a resource on only one node of a cluster at any one time.

宽集群锁。

Cluster wide locks have an asynchronous API unlike most lock APIs which block the calling thread until the lock is obtained.

宽集群锁有一个异步的方法不像大部分锁的api,它锁的时候会阻止访问线程直到锁成功。

To obtain a lock use getLock.

获取一个锁用getLock。

This won’t block, but when the lock is available, the handler will be called with an instance of Lock, signifying that you now own the lock.

这个不阻止,当锁有效,则handler会被执行,标示着你用了这个锁。

While you own the lock no other caller, anywhere on the cluster will be able to obtain the lock.

When you’ve finished with the lock, you call release to release it, so another caller can obtain it.

  1.  
    sd.getLock("mylock", res -> {
     
      if (res.succeeded()) {
     
        // Got the lock!
     
        Lock lock = res.result();
     
     
     
        // 5 seconds later we release the lock so someone else can get it
     
     
     
        vertx.setTimer(5000, tid -> lock.release());
     
     
     
      } else {
     
        // Something went wrong
     
      }
     
    });

You can also get a lock with a timeout. If it fails to obtain the lock within the timeout the handler will be called with a failure:

你可以延时来获取某个锁,如果获取锁超时失败了,会返回一个失败failure。

  1.  
    sd.getLockWithTimeout("mylock", 10000, res -> {
     
      if (res.succeeded()) {
     
        // Got the lock!
     
        Lock lock = res.result();
     
     
     
      } else {
     
        // Failed to get lock
     
      }
     
    });

Cluster-wide counters

集群计数器。

It’s often useful to maintain an atomic counter across the different nodes of your application.

如果你经常用一个原子的计数器在不同的节点之间。

You can do this with Counter.

你可以用Counter来做。

You obtain an instance with getCounter:

通过getCounter来获得。

  1.  
    sd.getCounter("mycounter", res -> {
     
      if (res.succeeded()) {
     
        Counter counter = res.result();
     
      } else {
     
        // Something went wrong!
     
      }
     
    });

Once you have an instance you can retrieve the current count, atomically increment it, decrement and add a value to it using the various methods.

一旦你获取了一个实例你可以获取当前计数,原子的,可增长,可减少的,可设置的通过各种方法。

See the API docs for more information.

免责声明:文章转载自《使用vertx共享数据》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇chart.js使用常见问题无法在Web服务器上启用调试...下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Android中的Handler机制

在android主线程中做太耗时的操作会引起ANR崩溃,为了进行线程间通信,就需要用到handler消息处理机制。消息传递分为两类,一种是从MainThread向WorkerThread传递消息,而另外一种是从WorkerThread向MainThread传递消息。由于主线程主要负责UI相关的事件,如用户的点击事件,屏幕触摸事件等,当捕捉到用户动作后将会分...

Vue3.x 推荐使用 mitt.js

Vue2.x 使用 EventBus 进行组件通信,而 Vue3.x 推荐使用 mitt.js。 比起 Vue 实例上的 EventBus,mitt.js 好在哪里呢?首先它足够小,仅有200bytes,其次支持全部事件的监听和批量移除,它还不依赖 Vue 实例,所以可以跨框架使用,React 或者 Vue,甚至 jQuery 项目都能使用同一套库。 快...

flask logger

Flask uses standard Python logging. All Flask-related messages are logged under the 'flask' logger namespace. Flask.loggerreturns the logger named 'flask.app', and can be used to...

安卓多线程的实现

有以下几种方式: 1)Activity.runOnUiThread(Runnable) 2)View.post(Runnable) ;View.postDelay(Runnable , long) 3)Handler 4)AsyncTask Android是单线程模型,这意味着Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行,所以你...

reactor设计模式

reactor设计模式,是一种基于事件驱动的设计模式。 《Pattern-Oriented Software Architecture, Volume 2》 对这个模式做了详细的讲解。 这个模式的结构图如下: 图中的handle对应的是操作系统提供的句柄,例如I/O句柄,Event_Handler类持有这些句柄, reactor类内部提供一个事件循环:h...

ASP.NET基础知识整理

Asp.net六大对象 1.Request-->读取客户端在Web请求期间发送的值 常用方法: 1、Request.UrlReferrer请求的来源,可以根据这个判断从百度搜的哪个关键词、防下载盗链、防图片盗链,可以伪造(比如迅雷)。 (使用全局一般处理程序) 2、Request.UserHostAddress获得访问者的IP地址 3、Reque...