RabbitConsumer.java 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package net.yaoyi.pipeline.rabbitmq;
  2. import com.aliyun.fc.runtime.Context;
  3. import com.aliyun.fc.runtime.PojoRequestHandler;
  4. import com.rabbitmq.client.Channel;
  5. import com.rabbitmq.client.Connection;
  6. import lombok.extern.slf4j.Slf4j;
  7. import net.yaoyi.pipeline.common.JacksonUtils;
  8. import okhttp3.*;
  9. import java.io.IOException;
  10. import java.nio.charset.StandardCharsets;
  11. import java.util.Map;
  12. import java.util.concurrent.TimeUnit;
  13. /**
  14. * RabbitMQ 消费者 - 阿里云函数计算实现
  15. */
  16. @Slf4j
  17. public class RabbitConsumer implements PojoRequestHandler<Map<String, Object>, Void> {
  18. private static final String PIPELINE_API = "http://1861991840278303.eventbridge.cn-beijing.aliyuncs.com/webhook/putEvents?token=62ed79329bb74d0d8ede5cc5d0487a45897a6ff99f5d4d61946daf9f6e9c7fbc766b9d55ef2241edb2c2cb3aee651ac101409d2783f341aa8e8d27fdb9869d86";
  19. private static final OkHttpClient httpClient = new OkHttpClient.Builder()
  20. .connectTimeout(10, TimeUnit.SECONDS)
  21. .readTimeout(30, TimeUnit.SECONDS)
  22. .writeTimeout(30, TimeUnit.SECONDS)
  23. .build();
  24. private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
  25. @Override
  26. public Void handleRequest(Map<String, Object> input, Context context) {
  27. log.info("函数计算启动, Request ID: {}, data:{}", context.getRequestId(), JacksonUtils.toJson(input));
  28. Map<String, Object> payload = (Map<String, Object>) input.get("payload");
  29. String queueName = payload.get("queueName").toString();
  30. try (Connection connection = RabbitMQHelper.createConnection();
  31. Channel channel = RabbitMQHelper.createChannel(connection, queueName)) {
  32. startConsumer(channel,queueName);
  33. log.info("RabbitMQ 消费者启动成功");
  34. Object val = payload.get("waitSeconds");
  35. if (val instanceof Integer) {
  36. Thread.sleep(((int) val) * 1000);
  37. } else {
  38. Thread.sleep(2 * 60 * 1000);
  39. }
  40. } catch (Exception e) {
  41. log.error("启动 RabbitMQ 消费者失败", e);
  42. throw new RuntimeException("启动失败: " + e.getMessage(), e);
  43. }
  44. return null;
  45. }
  46. /**
  47. * 启动消费者
  48. */
  49. private void startConsumer(Channel channel,String queueName) throws IOException {
  50. channel.basicQos(1);
  51. log.info("开始消费队列: {}", queueName);
  52. channel.basicConsume(queueName, false, (consumerTag, delivery) -> {
  53. String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
  54. log.info("收到消息: {}", message);
  55. try {
  56. processMessage(message);
  57. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
  58. log.info("消息处理成功并已确认");
  59. } catch (Exception e) {
  60. log.error("处理消息失败", e);
  61. channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
  62. log.warn("消息已重新入队");
  63. }
  64. },
  65. consumerTag -> log.info("消费者被取消: {}", consumerTag));
  66. }
  67. private void processMessage(String message) {
  68. RequestBody body = RequestBody.create(message, JSON);
  69. Request request = new Request.Builder().url(PIPELINE_API).put(body).build();
  70. try (Response response = httpClient.newCall(request).execute()) {
  71. if (response.isSuccessful()) {
  72. String responseBody = response.body() != null ? response.body().string() : "";
  73. log.info("Pipline API 请求成功:{}", responseBody);
  74. } else {
  75. log.info("Pipline API 请求失败:{}, body:{}", response.code(), response.body() != null ? response.body().string() : "");
  76. }
  77. } catch (Exception e) {
  78. log.error("Pipline API 请求异常", e);
  79. }
  80. }
  81. }