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

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

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

Connection.createSession介绍

[英]Creates a Session object, specifying no arguments.

The behaviour of the session that is created depends on whether this method is called in a Java SE environment, in the Java EE application client container, or in the Java EE web or EJB container. If this method is called in the Java EE web or EJB container then the behaviour of the session also depends on whether or not there is an active JTA transaction in progress.

In a Java SE environment or in the Java EE application client container:

  • The session will be non-transacted and received messages will be acknowledged automatically using an acknowledgement mode of Session.AUTO_ACKNOWLEDGE For a definition of the meaning of this acknowledgement mode see the link below.

In a Java EE web or EJB container, when there is an active JTA transaction in progress:

  • The session will participate in the JTA transaction and will be committed or rolled back when that transaction is committed or rolled back, not by calling the session's commit or rollback methods.

In the Java EE web or EJB container, when there is no active JTA transaction in progress:

  • The session will be non-transacted and received messages will be acknowledged automatically using an acknowledgement mode of Session.AUTO_ACKNOWLEDGE For a definition of the meaning of this acknowledgement mode see the link below.

Applications running in the Java EE web and EJB containers must not attempt to create more than one active (not closed) Session object per connection. If this method is called in a Java EE web or EJB container when an active Session object already exists for this connection then a JMSException will be thrown.
[中]创建会话对象,不指定任何参数。
创建的会话的行为取决于是在JavaSE环境中、在JavaEE应用程序客户机容器中还是在JavaEEWeb或EJB容器中调用此方法。如果在JavaEEWeb或EJB容器中调用此方法,那么会话的行为还取决于是否有正在进行的活动JTA事务。
在Java SE环境或Java EE应用程序客户端容器中:
*会话将是非事务性的,接收到的消息将使用会话确认模式自动确认。自动确认有关此确认模式含义的定义,请参阅下面的链接。
在Java EE web或EJB容器中,当存在正在进行的活动JTA事务时:
*会话将参与JTA事务,并在事务提交或回滚时提交或回滚,而不是通过调用会话的提交或回滚方法。
在Java EE web或EJB容器中,当没有正在进行的活动JTA事务时:
*会话将是非事务性的,接收到的消息将使用会话确认模式自动确认。自动确认有关此确认模式含义的定义,请参阅下面的链接。
在JavaEEWeb和EJB容器中运行的应用程序不得尝试为每个连接创建多个活动(未关闭)会话对象。如果在JavaEEWeb或EJB容器中调用此方法,而此连接已经存在活动会话对象,则会引发JMSException。

代码示例

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

protected void prepare() {
  if (this.options.jmsProvider == null || this.options.msgProducer == null) {
    throw new IllegalStateException("JMS Provider and MessageProducer not set.");
  }
  LOG.debug("Connecting JMS..");
  try {
    ConnectionFactory cf = this.options.jmsProvider.connectionFactory();
    Destination dest = this.options.jmsProvider.destination();
    this.connection = cf.createConnection();
    this.session = connection.createSession(this.options.jmsTransactional,
                        this.options.jmsAcknowledgeMode);
    this.messageProducer = session.createProducer(dest);
    connection.start();
  } catch (Exception e) {
    LOG.warn("Error creating JMS connection.", e);
  }
}

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

Destination dest = jmsProvider.destination();
this.connection = cf.createConnection();
this.session = connection.createSession(false, jmsAcknowledgeMode);
MessageConsumer consumer = session.createConsumer(dest);
consumer.setMessageListener(this);
this.connection.start();

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

/**
 * A variant of {@link #execute(SessionCallback, boolean)} that explicitly
 * creates a non-transactional {@link Session}. The given {@link SessionCallback}
 * does not participate in an existing transaction.
 */
@Nullable
private <T> T executeLocal(SessionCallback<T> action, boolean startConnection) throws JmsException {
  Assert.notNull(action, "Callback object must not be null");
  Connection con = null;
  Session session = null;
  try {
    con = createConnection();
    session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
    if (startConnection) {
      con.start();
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Executing callback on JMS Session: " + session);
    }
    return action.doInJms(session);
  }
  catch (JMSException ex) {
    throw convertJmsAccessException(ex);
  }
  finally {
    JmsUtils.closeSession(session);
    ConnectionFactoryUtils.releaseConnection(con, getConnectionFactory(), startConnection);
  }
}

代码示例来源:origin: kiegroup/jbpm

try {
  queueConnection = connectionFactory.createConnection();
  queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
  TextMessage message = queueSession.createTextMessage(eventXml);
  message.setStringProperty("LogType", "Task");
  producer = queueSession.createProducer(queue);  
  producer.setPriority(priority);
  producer.send(message);
} catch (Exception e) {
  throw new RuntimeException("Error when sending JMS message with working memory event", e);
      queueConnection.close();
    } catch (JMSException e) {
      logger.warn("Error when closing queue connection", e);

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

given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession);
given(txSession.getTransacted()).willReturn(true);
given(con.createSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession);
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close();
con1.start();
Connection con2 = scf.createConnection();
Session session2 = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close();
session2 = con2.createSession(true, Session.AUTO_ACKNOWLEDGE);
session2.commit();
session2.close();
con2.start();
con1.close();
con2.close();
verify(txSession).close();
verify(nonTxSession).close();
verify(con).start();
verify(con).stop();
verify(con).close();

代码示例来源: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: org.apache.logging.log4j/log4j-core

public JmsAppenderTest() throws Exception {
  // this needs to set up before LoggerContextRule
  given(connectionFactory.createConnection()).willReturn(connection);
  given(connectionFactory.createConnection(anyString(), anyString())).willThrow(IllegalArgumentException.class);
  given(connection.createSession(eq(false), eq(Session.AUTO_ACKNOWLEDGE))).willReturn(session);
  given(session.createProducer(eq(destination))).willReturn(messageProducer);
  given(session.createTextMessage(anyString())).willReturn(textMessage);
  given(session.createObjectMessage(isA(Serializable.class))).willReturn(objectMessage);
}

代码示例来源:origin: quartz-scheduler/quartz

sess = conn.createSession(useTransaction, ackMode);
  producer = sess.createProducer(destination);
  producer.send(msg);
} catch (final Exception e) {
  throw new JobExecutionException(e);

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

Mockito.when(session.createBytesMessage()).thenReturn(Mockito.mock(BytesMessage.class));
MessageProducer producer = Mockito.mock(MessageProducer.class);
Mockito.when(session.createProducer(queue)).thenReturn(producer);
Mockito.when(connection.createSession(Mockito.anyBoolean(), Mockito.anyInt())).thenReturn(session);
Mockito.when(this.jmsConnectionFactory.createConnection()).thenReturn(connection);

代码示例来源:origin: kiegroup/jbpm

try {
  queueConnection = connectionFactory.createConnection();
  queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
  TextMessage message = queueSession.createTextMessage(eventXml);
  message.setIntProperty("EventType", eventType);
  message.setStringProperty("LogType", "Process");
  producer = queueSession.createProducer(queue);  
  producer.setPriority(priority);
  producer.send(message);
} catch (Exception e) {
  throw new RuntimeException("Error when sending JMS message with working memory event", e);
      queueConnection.close();
    } catch (JMSException e) {
      logger.warn("Error when closing queue connection", e);

代码示例来源: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);
      messageSelector.isEmpty() ? null : messageSelector, true);
 } else {
  messageConsumer = session.createConsumer(destination,
      messageSelector.isEmpty() ? null : messageSelector);

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

scf.setReconnectOnException(false);
Connection con1 = scf.createTopicConnection();
Session session1 = con1.createSession(true, Session.AUTO_ACKNOWLEDGE);
session1.getTransacted();
session1 = con1.createSession(false, Session.CLIENT_ACKNOWLEDGE);
session1.close();
con1.start();
TopicConnection con2 = scf.createTopicConnection();
Session session2 = con2.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
session2.close();
con2.start();
con1.close();
con2.close();

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

given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
verify(con).close();

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

/**
   * Initializes JMS resources.
   */
  @Override
  public void prepare(Map<String, Object> topoConf, TopologyContext context,
            OutputCollector collector) {
    if (this.jmsProvider == null || this.producer == null) {
      throw new IllegalStateException("JMS Provider and MessageProducer not set.");
    }
    this.collector = collector;
    LOG.debug("Connecting JMS..");
    try {
      ConnectionFactory cf = this.jmsProvider.connectionFactory();
      Destination dest = this.jmsProvider.destination();
      this.connection = cf.createConnection();
      this.session = connection.createSession(this.jmsTransactional,
                          this.jmsAcknowledgeMode);
      this.messageProducer = session.createProducer(dest);

      connection.start();
    } catch (Exception e) {
      LOG.warn("Error creating JMS connection.", e);
    }
  }
}

代码示例来源:origin: kiegroup/jbpm

when(connection.createSession(true, Session.AUTO_ACKNOWLEDGE)).thenReturn(session);
when(session.createProducer(any())).thenReturn(producer);
when(session.createTextMessage(any())).thenReturn(message);

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

try {
  connection = cf.createConnection(userName, password);
  Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
  MessageProducer producer = session.createProducer(dest);
  ActiveMQTextMessage msg = (ActiveMQTextMessage) session.createTextMessage(body);
  producer.send(msg);
    connection.close();

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

given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer);  // no MessageSelector...
given(connection.createSession(this.container.isSessionTransacted(),
    this.container.getSessionAcknowledgeMode())).willReturn(session);
verify(connection).start();

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

Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE);
  tas.getTransacted();
  tas.close();
  tac.close();
verify(this.connection).start();
if (useTransactedTemplate()) {
  verify(this.session).commit();
verify(this.connection).close();

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

given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);
given(con.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session2);
verify(session).close();
verify(session2).close();
verify(con, times(2)).close();

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

@Before
public void setUp() throws Exception {
  brokerService = new BrokerService();
  brokerService.setPersistent(false);
  brokerService.start();
  factory =  new ActiveMQConnectionFactory(BrokerRegistry.getInstance().findFirst().getVmConnectorURI());
  producerConnection = factory.createConnection();
  producerConnection.start();
  producerSession = producerConnection.createSession(false,Session.AUTO_ACKNOWLEDGE);
  queue = producerSession.createQueue(getClass().getName());
  producer = producerSession.createProducer(queue);
}

相关文章