本文整理匯總了Java中io.vertx.core.eventbus.MessageConsumer.handler方法的典型用法代碼示例。如果您正苦於以下問題:Java MessageConsumer.handler方法的具體用法?Java MessageConsumer.handler怎麽用?Java MessageConsumer.handler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類io.vertx.core.eventbus.MessageConsumer
的用法示例。
在下文中一共展示了MessageConsumer.handler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: registerSingleConfigEntryProvider
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
/**
* Registers a handler for accessing single configuration keys (input: String, reply type: String). If no
* config value is present the consumer will reply with a NOT_FOUND failure.
* @param address the event bus address to register.
* @param eventBus the event bus.
* @return the consumer registered.
*/
public static MessageConsumer<String> registerSingleConfigEntryProvider(String address, EventBus eventBus){
MessageConsumer<String> consumer = eventBus.consumer(address);
consumer.handler(h -> {
String key = (String) h.body();
if (key == null) {
h.fail(HttpResponseStatus.BAD_REQUEST.code(), "Missing config key.");
} else {
String value = ConfigurationProvider.getConfiguration().getOrDefault(key, null);
if (value != null) {
h.reply(value);
} else {
h.fail(HttpResponseStatus.NOT_FOUND.code(), "Config key not found: " + key);
}
}
});
return consumer;
}
示例2: registerMultiConfigEntryProvider
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
/**
* Registers a handler for accessing multiple configuration keys (input: String[] (Json),
* reply type: Map<String,String></String,String> (Json).
* @param address the event bus address to register.
* @param eventBus the event bus.
* @return the consumer registered.
*/
public static MessageConsumer<String> registerMultiConfigEntryProvider(String address, EventBus eventBus){
MessageConsumer<String> consumer = eventBus.consumer(address);
consumer.handler(h -> {
String val = h.body();
Configuration config = ConfigurationProvider.getConfiguration();
Map<String,String> entries = new TreeMap<>();
if(val!=null){
String[] sections = Json.decodeValue(val, String[].class);
for (String section : sections) {
if(section!=null) {
entries.putAll(config.with(ConfigurationFunctions.section(section)).getProperties());
}
}
}else{
entries.putAll(config.getProperties());
}
h.reply(Json.encode(entries));
});
return consumer;
}
示例3: start
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Override
public void start() throws Exception {
super.start();
client = JDBCClient.create(vertx, dataSource);
eventBus.registerDefaultCodec(Book.class, new BookEncoder());
eventBus.registerDefaultCodec(Recipe.class, new RecipeEncoder());
eventBus.registerDefaultCodec((Class<ArrayList<Book>>) (Class<?>) ArrayList.class, new ListOfBookEncoder());
initDb();
MessageConsumer<Object> read = eventBus.consumer("de.nierbeck.vertx.jdbc.read"); //TODO: move those addresses to a "global" dict.
MessageConsumer<Object> write = eventBus.consumer("de.nierbeck.vertx.jdbc.write.add");
MessageConsumer<Object> update = eventBus.consumer("de.nierbeck.vertx.jdbc.write.update");
MessageConsumer<Object> delete = eventBus.consumer("de.nierbeck.vertx.jdbc.delete");
read.handler(this::handleRead);
write.handler(this::handleWrite);
update.handler(this::handleUpdate);
delete.handler(this::handleDelete);
}
示例4: start
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Override
public void start() throws Exception {
PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<String, Map<String, byte[]>>
expirePeriod = new PassiveExpiringMap.ConstantTimeToLiveExpirationPolicy<>(
1, TimeUnit.DAYS);
this.db = new PassiveExpiringMap<>( expirePeriod, new LinkedHashMap<>() );
this.topicsManager = new MQTTTopicsManagerOptimized();
MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(ADDRESS);
consumer.handler(message -> {
JsonObject request = message.body();
MultiMap headers = message.headers();
if (headers == null || !headers.contains("command")) {
message.reply(new JsonObject().put("error", "Invalid message: missing 'command' header"));
}
JsonObject response = new JsonObject();
String command = headers.get("command");
switch (command) {
case "saveRetainMessage":
response = saveRetainMessage(request);
break;
case "getRetainedMessagesByTopicFilter":
response = getRetainedMessagesByTopicFilter(request);
break;
case "deleteRetainMessage":
response = deleteRetainMessage(request);
break;
default:
response = doDefault(request);
break;
}
// System.out.println("instance => "+ this + "db.size => "+ db.size());
message.reply(response);
});
}
示例5: start
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Override
public void start() throws Exception {
super.start();
MessageConsumer<JsonArray> ebConsumer = vertx.eventBus()
.consumer(CommonConstants.VERTX_EVENT_BUS_HE_RSS_JDG_PUT);
ebConsumer.handler(this::processEntries);
}
示例6: scheduling
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
static void scheduling(Vertx vertx) {
EventBus eventBus = vertx.eventBus();
// Consumer of the timer events
MessageConsumer<JsonObject> consumer = eventBus.consumer("scheduler:timer");
// Listens and prints timer events. When timer completes stops the Vertx
consumer.handler (
message -> {
JsonObject event = message.body();
if (event.getString("event").equals("complete")) {
System.out.println("completed");
vertx.close();
}
else {
System.out.println(event);
}
}
);
// Create new timer
eventBus.send (
"chime",
(new JsonObject()).put("operation", "create").put("name", "scheduler:timer")
.put("publish", false).put("max count", 3)
.put("description", (new JsonObject()).put("type", "interval").put("delay", 1)),
ar -> {
if (ar.succeeded()) {
System.out.println("Scheduling started: " + ar.result().body());
}
else {
System.out.println("Message failed: " + ar.cause());
vertx.close();
}
}
);
}
示例7: initialize
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
private void initialize(Future<Void> done, String company, int numberOfShares,
Future<PortfolioService> retrieveThePortfolioService, Future<MessageConsumer<JsonObject>> retrieveTheMarket,
AsyncResult<CompositeFuture> ar) {
if (ar.failed()) {
done.fail(ar.cause());
} else {
PortfolioService portfolio = retrieveThePortfolioService.result();
MessageConsumer<JsonObject> consumer = retrieveTheMarket.result();
consumer.handler(message -> TraderUtils.dumbTradingLogic(company, numberOfShares, portfolio, message.body()));
done.complete();
}
}
示例8: registerConfigurationInjector
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
/**
* Registers a handler for configuring any objects sent via the message bus using Tamaya's injection API.
* @param address the event bus address to register.
* @param eventBus the event bus.
* @return the consumer registered.
*/
public static MessageConsumer<Object> registerConfigurationInjector(String address, EventBus eventBus){
MessageConsumer<Object> consumer = eventBus.consumer(address);
consumer.handler(h -> {
Object o = h.body();
if(o==null){
h.fail(HttpResponseStatus.BAD_REQUEST.code(), "Required object to configure is missing.");
}else {
ConfigurationInjection.getConfigurationInjector().configure(o);
h.reply("OK");
}
});
return consumer;
}
示例9: test
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Test
public void test() throws InterruptedException {
Random random = new Random();
vertx.setPeriodic(10, l -> {
vertx.eventBus().publish("data", random.nextDouble());
});
Record record = MessageSource.createRecord("Hello", "data");
discovery.publish(record, (r) -> {
});
await().until(() -> record.getRegistration() != null);
AtomicReference<Record> found = new AtomicReference<>();
discovery.getRecord(new JsonObject().put("name", "Hello"), ar -> {
found.set(ar.result());
});
await().until(() -> found.get() != null);
ServiceReference service = discovery.getReference(found.get());
MessageConsumer<Double> consumer = service.get();
List<Double> data = new ArrayList<>();
consumer.handler(message -> {
data.add(message.body());
});
await().until(() -> !data.isEmpty());
service.release();
int size = data.size();
Thread.sleep(500);
assertThat(data.size()).isEqualTo(size);
// Just there to be sure we can call it twice
service.release();
}
示例10: start
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Override
public void start(Future<Void> fut) throws Exception {
// Sensors
sensors.put(1, null);
sensors.put(2, null);
// W1 Bus init
W1Master w1Master = new W1Master();
// Get DS18B20 Temp device objects
for (TemperatureSensor device : w1Master.getDevices(TemperatureSensor.class)) {
if (device.getName().contains("28-0000062d006a")) sensor1 = device;
if (device.getName().contains("28-0000062d1425")) sensor2 = device;
}
// Read the 2 temp sensors "immediately"
readTemp(event -> fut.complete());
// .. and continue refreshing the 2 temp. sensors every minute
vertx.setPeriodic(2000, event -> {
readTemp(event1 -> log.info("Temp sensor reading ok : " + sensors.get(1) + " / " + sensors.get(2)));
});
// Handler to serve the sensors values on the vertx event loop
MessageConsumer<String> dhwConsumer = vertx.eventBus().consumer("sensor-temp");
dhwConsumer.handler(event -> {
String sensorId = event.body();
if (sensorId.equals("1")) {
event.reply(sensors.get(1));
}
else if (sensorId.equals("2")) {
event.reply(sensors.get(2));
}
else {
event.fail(-1, "Bad sensor Id");
}
});
}
示例11: handlePressure
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
/**
* Handle back-pressure on component.
*
* @param stream stream in read.
* @param endHandler end handler to call.
*/
public void handlePressure(ReadStream stream, Handler<Void> endHandler) {
MessageConsumer<String> consumer = eventBus.consumer(parentEndpoint + ".pressure");
consumer.handler(new PressureHandler(stream, parentEndpoint, h -> {
if (endHandler != null) {
endHandler.handle(null);
}
consumer.unregister();
}));
}
示例12: test
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@Test
public void test() throws InterruptedException {
Random random = new Random();
vertx.setPeriodic(10, l -> {
vertx.eventBus().publish("data", random.nextDouble());
});
Record record = MessageSource.createRecord("Hello", "data");
discovery.publish(record, (r) -> {
});
await().until(() -> record.getRegistration() != null);
AtomicReference<Record> found = new AtomicReference<>();
discovery.getRecord(new JsonObject().put("name", "Hello"), ar -> {
found.set(ar.result());
});
await().until(() -> found.get() != null);
Service service = DiscoveryService.getService(vertx, found.get());
MessageConsumer<Double> consumer = service.get();
List<Double> data = new ArrayList<>();
consumer.handler(message -> {
data.add(message.body());
});
await().until(() -> ! data.isEmpty());
service.release();
int size = data.size();
Thread.sleep(200);
assertThat(data.size()).isEqualTo(size);
}
示例13: registerMessageConsumer
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
/**
*
* @param <REQ>
* @param <RESP>
* @param config
* @return MessageConsumer
*/
protected <REQ extends Message, RESP extends Message> MessageConsumerRegistration<REQ, RESP> registerMessageConsumer(@NonNull final MessageConsumerConfig<REQ, RESP> config) {
Preconditions.checkState(!messageConsumerRegistrations.containsKey(config.getAddressMessageMapping().getAddress()));
final EventBus eventBus = vertx.eventBus();
registerMessageCodecs(config);
final String address = config.getAddressMessageMapping().getAddress();
final MessageConsumer<REQ> consumer = config.isLocal() ? eventBus.localConsumer(address) : eventBus.consumer(address);
consumer.completionHandler(config.getCompletionHandler().map(handler -> messageConsumerCompletionHandler(address, Optional.of(handler), config))
.orElseGet(() -> messageConsumerCompletionHandler(address, Optional.empty(), config)));
consumer.endHandler(config.getEndHandler().map(handler -> messageConsumerEndHandler(address, Optional.of(handler), config))
.orElseGet(() -> messageConsumerEndHandler(address, Optional.empty(), config)));
config.getExceptionHandler().ifPresent(consumer::exceptionHandler);
consumer.handler(messageConsumerHandler(config));
final String processSpecificAddress = config.getAddressMessageMapping().getProcessSpecificAddress();
final MessageConsumer<REQ> processSpecificConsumer = config.isLocal() ? eventBus.localConsumer(processSpecificAddress) : eventBus.consumer(processSpecificAddress);
processSpecificConsumer.completionHandler(config.getCompletionHandler().map(handler -> messageConsumerCompletionHandler(processSpecificAddress, Optional.of(handler), config))
.orElseGet(() -> messageConsumerCompletionHandler(processSpecificAddress, Optional.empty(), config)));
processSpecificConsumer.endHandler(config.getEndHandler().map(handler -> messageConsumerEndHandler(processSpecificAddress, Optional.of(handler), config))
.orElseGet(() -> messageConsumerEndHandler(processSpecificAddress, Optional.empty(), config)));
config.getExceptionHandler().ifPresent(processSpecificConsumer::exceptionHandler);
processSpecificConsumer.handler(messageConsumerHandler(config));
final MessageConsumerRegistration<REQ, RESP> messageConsumerRegistration = MessageConsumerRegistration.<REQ, RESP>builder()
.messageConsumer(consumer)
.processSpecificMessageConsumer(processSpecificConsumer)
.config(config)
.build();
messageConsumerRegistrations = ImmutableMap.<String, MessageConsumerRegistration<?, ?>>builder().putAll(messageConsumerRegistrations).put(
config.address(),
messageConsumerRegistration
).build();
return messageConsumerRegistration;
}
示例14: example11
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
public void example11(MessageConsumer<JsonObject> consumer) {
consumer.handler(msg -> {
// ...do something with received message...then reply...
String replyAddress = msg.replyAddress();
if(replyAddress != null) {
JsonObject amqpReplyMessagePayload = new JsonObject();
amqpReplyMessagePayload.put("body", "myResponse");
msg.reply(amqpReplyMessagePayload);
}
});
}
示例15: testReportToEventBus
import io.vertx.core.eventbus.MessageConsumer; //導入方法依賴的package包/類
@org.junit.Test
public void testReportToEventBus() {
MessageConsumer<JsonObject> consumer = vertx.eventBus().<JsonObject>consumer("the_address");
consumer.handler(msg -> {
if (msg.body().getString("type").equals(EventBusCollector.EVENT_TEST_SUITE_END)) {
consumer.unregister();
testComplete();
}
});
consumer.completionHandler(ar -> {
assertTrue(ar.succeeded());
suite.run(vertx, new TestOptions().addReporter(new ReportOptions().setTo("bus:the_address")));
});
await();
}