AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 78443626
Accepted
Undertaker
Undertaker
Asked: 2024-05-07 23:31:57 +0800 CST2024-05-07 23:31:57 +0800 CST 2024-05-07 23:31:57 +0800 CST

Teste com ActiveMQ Server integrado com cliente Vertex Broker

  • 772

Estou usando o ActiveMQ Artemis com o cliente Vertex Broker. Quero testar o código abaixo:

public class ActiveMqMessageSender {

  private String queue = "myQueue";

  public void sendMessage(String message) throws ExecutionException, InterruptedException {
    AmqpMessage msg =
        AmqpMessage.create()
            .withBody(message)
            .build();
    client = createAmqpClient();
    var amqpConnectionFuture = client.connect();
    // Wait here to ensure that the connection is successful.
    var amqpConnection = amqpConnectionFuture.toCompletionStage().toCompletableFuture().get();
    log.info("Vert.x AMQP connection created successfully.");

    var amqpSenderFuture = amqpConnection.createSender(queue);
    // Wait here to ensure that the connection is successful.
    var amqpSender = amqpSenderFuture.toCompletionStage().toCompletableFuture().get();
    log.info("Vert.x AMQP sender created successfully.");

    amqpSender.sendWithAck(msg, ackResult -> {
      if (ackResult.succeeded()) {
        log.info("Message sent successfully.");
      } else {
        log.error("Failed to send message: " + ackResult.cause().getMessage());
      }
    });
  }

  private AmqpClient createAmqpClient() {
    var options =
        new AmqpClientOptions()
            .setHost("localhost")
            .setPort("61616")
            .setUsername("test")
            .setPassword("test");
    return AmqpClient.create(options);
  }

No meu teste JUnit:

@SpringBootTest
class ActiveMqMessageSenderTest {

  private String queue = "myQueue";

  @Autowired
  private ActiveMqMessageSender messageSender;
  private static EmbeddedActiveMQExtension embeddedActiveMQ;

  @BeforeAll
  public static void setUp() throws Exception {
    Configuration configuration =
        new ConfigurationImpl().setName("embedded-server")
            .setPersistenceEnabled(false)
            .setSecurityEnabled(false)
            .addAcceptorConfiguration("default", "tcp://localhost:61616")
            .addAddressSetting("#",
                new AddressSettings().setDeadLetterAddress(SimpleString.toSimpleString("dla"))
                    .setExpiryAddress(SimpleString.toSimpleString("expiry")));

    // Start the embedded ActiveMQ Artemis server
    embeddedActiveMQ = new EmbeddedActiveMQExtension(configuration);
    embeddedActiveMQ.start();
  }

  @AfterAll
  public static void tearDown() throws Exception {
    // Stop the embedded ActiveMQ Artemis server
    if (embeddedActiveMQ != null) {
      embeddedActiveMQ.stop();
    }
  }

  @Test
  void testSendMessage() throws Exception {

    String message = "Test Message";
    messageSender.sendMessage(message);

  }
}

Meu application.yml se parece com

  artemis:
    broker:
      host: localhost
      port: 61616
      username: artemis
      password: artemis

Quando executo um servidor ActiveMQ local, o código funciona. Mas quando tento executar o servidor incorporado via JUnit, vejo o seguinte nos logs:

[Test worker] INFO org.apache.activemq.artemis.core.server -- AMQ221020: Started NIO Acceptor at localhost:61616 for protocols [CORE]
[Test worker] INFO org.apache.activemq.artemis.core.server -- AMQ221007: Server is now live
[Test worker] INFO org.apache.activemq.artemis.core.server -- AMQ221001: Apache ActiveMQ Artemis Message Broker version 2.31.2 [embedded-server, nodeID=9df62ceb-0c83-11ef-a6a7-00155ddd1843]

Neste ponto espera:

INFO   [Thread-1 (activemq-netty-threads)] org.apache.activemq.audit.resource - AMQ601767: CORE connection a6e64464 for user [email protected]:54291 created

E finalmente recebo:

WARN   [Thread-1 (ActiveMQ-server-org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl$6@72f3f14c)] o.a.activemq.artemis.core.client - AMQ212037: Connection failure to /127.0.0.1:54291 has been detected: AMQ229014: Did not receive data from /127.0.0.1:54291 within the 60000ms connection TTL. The connection will now be closed. [code=CONNECTION_TIMEDOUT]

io.vertx.core.VertxException: Disconnected
java.util.concurrent.ExecutionException: io.vertx.core.VertxException: Disconnected

Parece que a conexão com o servidor estava ok, mas quando tento conectar o cliente ligando client.connect()não funciona.

junit
  • 1 1 respostas
  • 13 Views

1 respostas

  • Voted
  1. Best Answer
    Justin Bertram
    2024-05-08T01:47:58+08:002024-05-08T01:47:58+08:00

    Acredito que o problema é que seu corretor incorporado não oferece suporte a AMQP. Quando o corretor incorporado é iniciado, você pode ver que ele registra isto:

    AMQ221020: Started NIO Acceptor at localhost:61616 for protocols [CORE]
    

    Observe, apenas COREé suportado. AMQPnão está incluído.

    Você precisa incluir org.apache.activemq:artemis-amqp-protocolno seu classpath. O corretor descobrirá isso automaticamente e o carregará para que suporte conexões AMQP 1.0.

    • 1

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve