javax.jms.Connection.setClientID()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(217)

本文整理了Java中javax.jms.Connection.setClientID()方法的一些代码示例,展示了Connection.setClientID()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Connection.setClientID()方法的具体详情如下:
包路径:javax.jms.Connection
类名称:Connection
方法名:setClientID

Connection.setClientID介绍

[英]Sets the client identifier for this connection.

The preferred way to assign a JMS client's client identifier is for it to be configured in a client-specific ConnectionFactoryobject and transparently assigned to the Connection object it creates.

Alternatively, a client can set a connection's client identifier using a provider-specific value. The facility to set a connection's client identifier explicitly is not a mechanism for overriding the identifier that has been administratively configured. It is provided for the case where no administratively specified identifier exists. If one does exist, an attempt to change it by setting it must throw an IllegalStateException. If a client sets the client identifier explicitly, it must do so immediately after it creates the connection and before any other action on the connection is taken. After this point, setting the client identifier is a programming error that should throw an IllegalStateException.

The purpose of the client identifier is to associate a connection and its objects with a state maintained on behalf of the client by a provider. The only such state identified by the JMS API is that required to support durable subscriptions.

If another connection with the same clientID is already running when this method is called, the JMS provider should detect the duplicate ID and throw an InvalidClientIDException.

This method must not be used in a Java EE web or EJB application. Doing so may cause a JMSException to be thrown though this is not guaranteed.
[中]设置此连接的客户端标识符。
分配JMS客户机的客户机标识符的首选方法是在特定于客户机的ConnectionFactoryobject中配置它,并透明地分配给它创建的连接对象。
或者,客户端可以使用特定于提供程序的值设置连接的客户端标识符。显式设置连接的客户端标识符的功能不是覆盖已通过管理配置的标识符的机制。它用于不存在管理指定的标识符的情况。如果确实存在,则试图通过设置它来更改它必须抛出非法状态异常。如果客户机显式设置客户机标识符,则必须在创建连接后以及对连接执行任何其他操作之前立即设置。在这一点之后,设置客户机标识符是一个编程错误,应该抛出一个IllegalStateException。
客户端标识符的目的是将连接及其对象与提供者代表客户端维护的状态相关联。JMS API标识的唯一此类状态是支持持久订阅所需的状态。
如果调用此方法时另一个具有相同clientID的连接已经在运行,JMS提供程序应该检测到重复ID并抛出InvalidClientIndexception。
此方法不得用于JavaEEWeb或EJB应用程序中。这样做可能会导致抛出JMSException,但这并不能保证。

代码示例

代码示例来源:origin: apache/nifi

public static Connection createConnection(final ProcessContext context, final String clientId) throws JMSException {
  Objects.requireNonNull(context);
  Objects.requireNonNull(clientId);
  final ConnectionFactory connectionFactory = createConnectionFactory(context);
  final String username = context.getProperty(USERNAME).getValue();
  final String password = context.getProperty(PASSWORD).getValue();
  final Connection connection = (username == null && password == null) ? connectionFactory.createConnection() : connectionFactory.createConnection(username, password);
  connection.setClientID(clientId);
  connection.start();
  return connection;
}

代码示例来源:origin: apache/flume

connection.setClientID(clientId.get());
 connection.start();
} catch (JMSException e) {
 throw new FlumeException("Could not create connection to broker", e);
 session = connection.createSession(true, Session.SESSION_TRANSACTED);
} catch (JMSException e) {
 throw new FlumeException("Could not create session", e);
  messageConsumer = session.createDurableSubscriber(
      (Topic) destination, durableSubscriptionName,
      messageSelector.isEmpty() ? null : messageSelector, true);

代码示例来源:origin: apache/activemq

@Test(timeout = 60000)
public void testStealLinkFails() throws Exception {
  final String clientID = "ThisIsAClientId";
  ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(unstealableConnectionURI);
  Connection connection1 = factory.createConnection();
  connection1.setClientID(clientID);
  connection1.start();
  try {
    Connection connection2 = factory.createConnection();
    connection2.setClientID(clientID);
    connection2.start();
    fail("Should not have been able to steal the link.");
  } catch (InvalidClientIDException e) {
    LOG.info("Caught expected error on trying to steal link: {}", e.getMessage());
    LOG.trace("Error: ", e);
  }
}

代码示例来源:origin: com.ksc.mission.base/jms

@Override
public void init() {
  try {
    connection = connectionFactory.createConnection();
    connection.setClientID(getId());
    connection.start();
    senderSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    publisherSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  } catch (JMSException e) {
    e.printStackTrace();
  }
  
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testWithConnectionFactoryAndClientId() throws JMSException {
  ConnectionFactory cf = mock(ConnectionFactory.class);
  Connection con = mock(Connection.class);
  given(cf.createConnection()).willReturn(con);
  SingleConnectionFactory scf = new SingleConnectionFactory(cf);
  scf.setClientId("myId");
  Connection con1 = scf.createConnection();
  Connection con2 = scf.createConnection();
  con1.start();
  con2.start();
  con1.close();
  con2.close();
  scf.destroy();  // should trigger actual close
  verify(con).setClientID("myId");
  verify(con).start();
  verify(con).stop();
  verify(con).close();
  verifyNoMoreInteractions(con);
}

代码示例来源:origin: apache/activemq-artemis

static TopicSubscriber createDurableSubscriber(final Connection connection,
                       final Topic topic,
                       final String clientID,
                       final String subscriptionName,
                       final int ackMode) throws JMSException {
 connection.setClientID(clientID);
 Session s = connection.createSession(false, ackMode);
 return s.createDurableSubscriber(topic, subscriptionName);
}

代码示例来源:origin: apache/nifi

private void unsubscribe(final String url, final String username, final String password, final String subscriptionId, final String jmsProvider, final int timeoutMillis) throws JMSException {
  final Connection connection;
  if (username == null && password == null) {
    connection = JmsFactory.createConnectionFactory(url, timeoutMillis, jmsProvider).createConnection();
  } else {
    connection = JmsFactory.createConnectionFactory(url, timeoutMillis, jmsProvider).createConnection(username, password);
  }
  Session session = null;
  try {
    connection.setClientID(subscriptionId);
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    session.unsubscribe(subscriptionId);
    getLogger().info("Successfully unsubscribed from {}, Subscription Identifier {}", new Object[]{url, subscriptionId});
  } finally {
    if (session != null) {
      try {
        session.close();
      } catch (final Exception e1) {
        getLogger().warn("Unable to close session with JMS Server due to {}; resources may not be cleaned up appropriately", new Object[]{e1});
      }
    }
    try {
      connection.close();
    } catch (final Exception e1) {
      getLogger().warn("Unable to close connection to JMS Server due to {}; resources may not be cleaned up appropriately", new Object[]{e1});
    }
  }
}

代码示例来源:origin: apache/activemq-artemis

@Test(timeout = 5000, expected = JMSException.class)
public void testInvalidClientIdSetConnection() throws Exception {
 Connection con = cf.createConnection();
 try {
   con.setClientID("invalid");
 } finally {
   try {
    con.close();
   } catch (Exception ignored) {
   }
 }
}

代码示例来源:origin: org.apache.activemq/activemq-optional

protected Session createSession(Connection connection) throws Exception {
  if (durable) {
    connection.setClientID(clientID);
  }
  Session session = connection.createSession(transacted, ackMode);
  if (topic) {
    destination = session.createTopic(subject);
  } else {
    destination = session.createQueue(subject);
  }
  return session;
}

代码示例来源:origin: com.github.hqstevenson.junit/activemq-junit

/**
 * Manually start the Client.
 */
public void start() {
  try {
    try {
      connection = connectionFactory.createConnection();
      String clientId = getClientId();
      if (clientId != null) {
        connection.setClientID(clientId);
      }
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      createClient();
    } catch (JMSException jmsEx) {
      throw new RuntimeException("Producer initialization failed" + this.getClass().getSimpleName(), jmsEx);
    }
    connection.start();
  } catch (JMSException jmsEx) {
    throw new IllegalStateException("Producer failed to start", jmsEx);
  }
  log.info("Ready to produce messages to {}", connectionFactory.getBrokerURL());
}

代码示例来源:origin: org.apache.apex/malhar-library

/**
 *  Connection specific setup for JMS.
 *
 *  @throws JMSException
 */
public void createConnection() throws JMSException
{
 connection = getConnectionFactory().createConnection();
 if (durable && clientId != null) {
  connection.setClientID(clientId);
 }
 logger.debug("Before starting connection.");
 connection.start();
 logger.debug("After starting connection.");
 // Create session
 session = connection.createSession(transacted, getSessionAckMode(ackMode));
 // Create destination
 destination = topic ? session.createTopic(subject) : session.createQueue(subject);
}

代码示例来源:origin: apache/activemq-artemis

@Test(timeout = 5000)
public void testValidIdSetConnection() throws Exception {
 Connection con = cf.createConnection();
 try {
   con.setClientID("valid");
   con.start();
 } finally {
   con.close();
 }
}

代码示例来源:origin: apache/ignite

connection.setClientID(clientId.trim());
connection.start();

代码示例来源:origin: apache/activemq-artemis

@Test
public void testInvalidSelectorException() throws Exception {
 Connection c = createConnection();
 c.setClientID("sofiavergara");
 Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 try {
   s.createDurableSubscriber(ActiveMQServerTestCase.topic1, "mysubscribption", "=TEST 'test'", true);
   ProxyAssertSupport.fail("this should fail");
 } catch (InvalidSelectorException e) {
   // OK
 }
}

代码示例来源:origin: apache/activemq-artemis

@Test
public void testDurableSubscriptionInvalidUnsubscribe() throws Exception {
 final String CLIENT_ID1 = "test-client-id1";
 Connection conn1 = null;
 try {
   conn1 = createConnection();
   conn1.setClientID(CLIENT_ID1);
   Session sess1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
   try {
    sess1.unsubscribe("non-existent subscription");
    ProxyAssertSupport.fail();
   } catch (JMSException e) {
   }
 } finally {
   if (conn1 != null) {
    conn1.close();
   }
 }
}

代码示例来源:origin: apache/activemq-artemis

@Test
public void testSetClientID() throws Exception {
 Connection connection = createConnection();
 final String clientID = "my-test-client-id";
 connection.setClientID(clientID);
 ProxyAssertSupport.assertEquals(clientID, connection.getClientID());
 Connection connection2 = createConnection();
 try {
   connection2.setClientID(clientID);
   Assert.fail("setClientID was expected to throw an exception");
 } catch (JMSException e) {
   // expected
 }
 connection.close();
 connection2.setClientID(clientID);
}

代码示例来源:origin: apache/activemq

final String clientID = "ThisIsAClientId";
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(stealableConnectionURI);
Connection connection1 = factory.createConnection();
connection1.setClientID(clientID);
connection1.start();
  Connection connection2 = factory.createConnection();
  connection2.setClientID(clientID);
  connection2.start();
} catch (InvalidClientIDException e) {
  LOG.info("Should not have failed while stealing the link: {}", e.getMessage());

代码示例来源:origin: apache/activemq-artemis

@Test
public void testSetSameIdToDifferentConnections() throws Exception {
 String id = "somethingElse" + name.getMethodName();
 conn = cf.createConnection();
 conn2 = cf.createConnection();
 conn.getClientID();
 conn.setClientID(id);
 try {
   conn2.setClientID(id);
   Assert.fail("should not happen.");
 } catch (InvalidClientIDException expected) {
   // expected
 }
 Session session1 = conn.createSession();
 Session session2 = conn.createSession();
 session1.close();
 session2.close();
}

代码示例来源:origin: apache/activemq-artemis

private void reconnect() throws Exception {
 connection = cf.createConnection();
 connection.setClientID("cid");
 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 subscriber1 = session.createDurableSubscriber(topic1, "subscriber-1");
 subscriber2 = session.createDurableSubscriber(topic1, "subscriber-2");
 connection.start();
}

代码示例来源:origin: apache/activemq-artemis

@Override
@Before
public void setUp() throws Exception {
 super.setUp();
 serverConnection = createConnection();
 serverConnection.setClientID("serverConnection:" + name.getMethodName());
 serverSession = serverConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 replyProducer = serverSession.createProducer(null);
 requestDestination = createDestination(serverSession);
 /* build queues */
 System.out.println("Creating consumer on: " + requestDestination);
 final MessageConsumer requestConsumer = serverSession.createConsumer(requestDestination);
 if (useAsyncConsume) {
   requestConsumer.setMessageListener(this);
 } else {
   Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
      syncConsumeLoop(requestConsumer);
    }
   });
   thread.start();
 }
 serverConnection.start();
}

相关文章