Simple RPC service based on message middleware RabbitMQ, summary of springboot startup principle

2.2 Listen to the queue and give feedback

  1. /**

  2. * 开启server

  3. */

  4. private void startServer() {

  5. try {

  6. LOG.info("Waiting for RPC calls.....");

  7. while (true) {

  8. //获得文本消息

  9. QueueingConsumer.Delivery delivery = consumer.nextDelivery();

  10. BasicProperties props = delivery.getProperties();

  11. //返回消息的属性

  12. BasicProperties replyProps = new BasicProperties.Builder()

  13. .correlationId(props.getCorrelationId())

  14. .build();

  15. long receiveTime = System.currentTimeMillis();

  16. JSONObject json = new JSONObject();

  17. try {

  18. String message = new String(delivery.getBody(), "UTF-8");

  19. int n = Integer.parseInt(message);

  20. LOG.info("Got a request: fib(" + message + ")");

  21. json.put("status", "success");

  22. json.put("result", fib(n));

  23. } catch (Exception e) {

  24. json.put("status", "fail");

  25. json.put("reason", "Not a Number!");

  26. LOG.error("receive message failed!", e);

  27. } finally {

  28. long responseTime = System.currentTimeMillis();

  29. json.put("calculateTime", (responseTime - receiveTime));

  30. channel.basicPublish("", props.getReplyTo(), replyProps, json.toString().getBytes("UTF-8"));

  31. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

  32. }

  33. }

  34. } catch (Exception e) {

  35. LOG.error("server failed!", e);

  36. } finally {

  37. if (connection != null) {

  38. try {

  39. connection.close();

  40. } catch (Exception e) {

  41. LOG.error("close failed!", e);

  42. }

  43. }

  44. }

  45. }

An infinite loop is used in this method, processing one message at a time. Get the latest message of the RabbitMQ queue by calling the nextDelivery method of the consumer object. At the same time, the feedback information attribute in the message is obtained through getProperties, which is used to mark the attribute of the client Client. Then calculate the result of the Fibonacci sequence.
The message is finally acknowledged to RabbitMQ using a message envelope via basicAck.

So far, the server side of the RPC service for calculating Fibonacci sequence has been realized.

3. Implementation of RPCClient

3.1 Initialize CLient

  1. /**

  2. * 消息请求的队列名、交换机名、路由键

  3. */

  4. private static final String EXCHANGE_NAME = "rpc_exchange";

  5. private static final String QUEUE_NAME = "request_rpc_queue";

  6. private static final String ROUTING_KEY = "rpc_routing_key";

  7. /**

  8. * 消息返回的队列名、交换机名、路由键

  9. */

  10. private static final String RESPONSE_QUEUE = "response_rpc_queue";

  11. private static final String RESPONSE_ROUTING_KEY = "response_rpc_routing_key";

  12. /**

  13. * RabbitMQ的实体

  14. */

  15. private Connection connection = null;

  16. private Channel channel = null;

  17. private QueueingConsumer consumer = null;

  18. /**

  19. * 构造客户端

  20. * @throws Exception

  21. */

  22. private RPCClient() throws Exception {

  23. ConnectionFactory factory = new ConnectionFactory();

  24. factory.setHost(Config.HOST);

  25. factory.setPort(Config.PORT);

  26. factory.setUsername(Config.USER);

  27. factory.setPassword(Config.PASSWORD);

  28. connection = factory.newConnection();

  29. channel = connection.createChannel();

  30. channel.exchangeDeclare(EXCHANGE_NAME, "direct");

  31. channel.queueDeclare(QUEUE_NAME, false, false, false, null);

  32. channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

  33. channel.queueDeclare(RESPONSE_QUEUE, false, false, false, null);

  34. channel.queueBind(RESPONSE_QUEUE, EXCHANGE_NAME, RESPONSE_ROUTING_KEY);

  35. consumer = new QueueingConsumer(channel);

  36. channel.basicConsume(RESPONSE_QUEUE, true, consumer);

  37. }

The way to declare the AMQP structure here is similar to that on the server side, except that the client side needs to declare an additional queue for RPC re

"Analysis of Java interview questions in first-line manufacturers + back-end development study notes + latest architecture explanation video + actual project source code handouts"

[docs.qq.com/doc/DSmxTbFJ1cmN1R2dB] Full content open source sharing

sponse。

3.2 Send/receive messages

  1. /**

  2. * 请求server

  3. * @param message

  4. * @return

  5. * @throws Exception

  6. */

  7. private String requestMessage(String message) throws Exception {

  8. String response = null;

  9. String corrId = UUID.randomUUID().toString();

  10. BasicProperties props = new BasicProperties.Builder().correlationId(corrId).replyTo(RESPONSE_QUEUE).build();

  11. channel.basicPublish("", QUEUE_NAME, props, message.getBytes("UTF-8"));

  12. while (true) {

  13. QueueingConsumer.Delivery delivery = consumer.nextDelivery();

  14. if (delivery.getProperties().getCorrelationId().equals(corrId)) {

  15. response = new String(delivery.getBody(),"UTF-8");

  16. break;

  17. }

  18. }

  19. return response;

  20. }

BasicProperties is used to store the attributes of your request message. Here I set the correlationId and replyTo attributes for the return identification on the server side.

4. Run the tests

The client sends:

The server receives and processes:

Client receives the calculation result:

Since the server I run RabbitMQ is rented from Alibaba Cloud, the transmission delay is about 60ms. If the RPC service and message middleware are deployed in the same computer room, the delay is basically at the ms level.

5. FAQ

5.1 Description

To experience the complete process, you need the following environment:

  1. JDK1.6以上 + Maven+ RabbitMQ

5.2 Source code

Please stamp the complete code code: github: https://github.com/chadwick521/rabbitmqdemo

The code of Server is in:

  1. rpc.RPCServer

About 60ms, if the RPC service and message middleware are deployed in the same computer room, the delay is basically at the ms level.

5. FAQ

5.1 Description

To experience the complete process, you need the following environment:

  1. JDK1.6以上 + Maven+ RabbitMQ

5.2 Source code

Please stamp the complete code code: github: https://github.com/chadwick521/rabbitmqdemo

The code of Server is in:

  1. rpc.RPCServer

Guess you like

Origin blog.csdn.net/m0_65484000/article/details/122133420