当前位置:网站首页>Rabbit MQ message sending of vertx
Rabbit MQ message sending of vertx
2022-07-05 01:46:00 【Xiong Da believed what Xiong er said】
Introduce
Vert.x RabbitMQ client , Allow applications to interact with RabbitMQ Agent interactive Vert.x client (AMQP 0.9.1)
1. maven Project dependence
<dependencies> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-web</artifactId> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-rabbitmq-client</artifactId> </dependency> <dependency> <groupId>io.vertx</groupId> <artifactId>vertx-config-yaml</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.lance.common</groupId> <artifactId>vertx-common-core</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency></dependencies>
2.YAML File configuration
server: host: 127.0.0.1 port: 18005rabbit: host: 127.0.0.1 port: 18003 username: root password: root virtualHost: /root connectionTimeout: 6000 requestedHeartbeat: 60 handshakeTimeout: 6000 requestedChannelMax: 5 networkRecoveryInterval: 500 automaticRecoveryEnabled: true
3. Start loading profile , And into the config In the middle
public class RabbitmqApplication { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); ConfigRetriever retriever = readYaml(vertx); retriever.getConfig(json -> { JsonObject object = json.result(); ClientHelper dbHelper = new ClientHelper(object.getJsonObject("rabbit"), vertx); dbHelper.afterPropertiesSet(); DeploymentOptions options = new DeploymentOptions().setConfig(object); vertx.deployVerticle(MainApp.class.getName(), options); }); } private static ConfigRetriever readYaml(Vertx vertx) { ConfigStoreOptions store = new ConfigStoreOptions() .setType("file") .setFormat("yaml") .setOptional(true) .setConfig(new JsonObject().put("path", "application.yaml")); return ConfigRetriever.create(vertx, new ConfigRetrieverOptions().addStore(store)); }}
4.RabbitMQ client Connection configuration
public class ClientHelper { private final JsonObject object; private final Vertx vertx; @Getter private static RabbitMQClient client; /** * initialization mail client Connect */ public void afterPropertiesSet() { ConfigProperties.MqProperties prop = object.mapTo(ConfigProperties.MqProperties.class); RabbitMQOptions config = new RabbitMQOptions(); // Each parameter is optional // The default parameter with be used if the parameter is not set config.setUser(prop.getUsername()); config.setPassword(prop.getPassword()); config.setHost(prop.getHost()); config.setPort(prop.getPort()); config.setVirtualHost(prop.getVirtualHost()); config.setReconnectAttempts(prop.getReconnectAttempts()); config.setReconnectInterval(prop.getReconnectInterval()); config.setConnectionTimeout(prop.getConnectionTimeout()); config.setRequestedHeartbeat(prop.getRequestedHeartbeat()); config.setHandshakeTimeout(prop.getHandshakeTimeout()); config.setRequestedChannelMax(prop.getRequestedChannelMax()); config.setNetworkRecoveryInterval(prop.getNetworkRecoveryInterval()); config.setAutomaticRecoveryEnabled(prop.isAutomaticRecoveryEnabled()); client = RabbitMQClient.create(vertx, config); // Connect client.start(asyncResult -> { if (asyncResult.succeeded()) { consumer(); log.warn("RabbitMQ successfully connected!"); } else { log.error("Fail to connect to RabbitMQ {}", asyncResult.cause().getMessage()); } }); } private void consumer() { client.basicConsumer(MqConst.HELLO_ROUTING_KEY, result -> { if (result.succeeded()) { RabbitMQConsumer mqConsumer = result.result(); mqConsumer.handler(message -> { log.info("Got message: {}", message.body().toString()); log.info("Message[exchange: {}, routeKey: {}] receive success!", message.envelope().getExchange(), message.envelope().getRoutingKey()); }); } else { log.error("===>Queue receive fail: ", result.cause()); } }); }}
5.Email Send execution instance
public class UserService { /** * send text content */ public void sendMessage(RoutingContext ctx) { UserVo userVo = ctx.getBodyAsJson().mapTo(UserVo.class); Buffer message = Buffer.buffer(Json.encode(userVo)); ClientHelper.getClient().basicPublish(MqConst.HELLO_EXCHANGE, MqConst.HELLO_ROUTING_KEY, message, result -> { if (result.succeeded()) { log.info("Message[exchange: {}, routeKey: {}] published success!", MqConst.HELLO_EXCHANGE, MqConst.HELLO_ROUTING_KEY); } else { log.error("Message send fail: ", result.cause()); } }); ctx.json(R.success("success")); }}
6. journal
2022-02-13 14:43:13.826 INFO 24 --- [ntloop-thread-1] com.lance.rabbit.service.UserService ---[ 30] : Message[exchange: hello_exchange, routeKey: hello_route_key] published success!2022-02-13 14:43:13.893 INFO 19 --- [ntloop-thread-0] com.lance.rabbit.config.ClientHelper ---[ 67] : Got message: {"name":"Jim Green","title":"book"}2022-02-13 14:43:13.893 INFO 19 --- [ntloop-thread-0] com.lance.rabbit.config.ClientHelper ---[ 68] : Message[exchange: hello_exchange, routeKey: hello_route_key] receive success!
7. Full address of the project
边栏推荐
- Introduction to the gtid mode of MySQL master-slave replication
- 220213c language learning diary
- [Digital IC hand tearing code] Verilog edge detection circuit (rising edge, falling edge, double edge) | topic | principle | design | simulation
- Hedhat firewall
- Five ways to query MySQL field comments!
- Are you still writing the TS type code
- Yyds dry goods inventory [Gan Di's one week summary: the most complete and detailed in the whole network]; detailed explanation of MySQL index data structure and index optimization; remember collectio
- Do you know the eight signs of a team becoming agile?
- es使用collapseBuilder去重和只返回某个字段
- Win: add general users to the local admins group
猜你喜欢
R语言用logistic逻辑回归和AFRIMA、ARIMA时间序列模型预测世界人口
runc hang 导致 Kubernetes 节点 NotReady
Roads and routes -- dfs+topsort+dijkstra+ mapping
【CTF】AWDP总结(Web)
微信小程序:全网独家小程序版本独立微信社群人脉
小程序容器技术与物联网 IoT 可以碰撞出什么样的火花
微信小程序;胡言乱语生成器
MySQL backup and recovery + experiment
Application and Optimization Practice of redis in vivo push platform
Win:使用 Shadow Mode 查看远程用户的桌面会话
随机推荐
Change the background color of a pop-up dialog
Comment mettre en place une équipe technique pour détruire l'entreprise?
微信小程序:微群人脉微信小程序源码下载全新社群系统优化版支持代理会员系统功能超高收益
Es uses collapsebuilder to de duplicate and return only a certain field
PHP Basics - detailed explanation of DES encryption and decryption in PHP
Include rake tasks in Gems - including rake tasks in gems
Practice of tdengine in TCL air conditioning energy management platform
What is the length of SHA512 hash string- What is the length of a hashed string with SHA512?
Outlook: always prompt for user password
Runc hang causes the kubernetes node notready
Heartless sword English translation of Xi Murong's youth without complaint
Main window in QT application
Redis master-slave replication cluster and recovery ideas for abnormal data loss # yyds dry goods inventory #
Word processing software
线上故障突突突?如何紧急诊断、排查与恢复
Introduction to redis (1)
Interpretation of mask RCNN paper
Do you know the eight signs of a team becoming agile?
es使用collapseBuilder去重和只返回某个字段
After reading the average code written by Microsoft God, I realized that I was still too young