Created
February 5, 2012 00:28
-
-
Save milenkovicm/1741385 to your computer and use it in GitHub Desktop.
send message using singlton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.e.test.service.first.controller; | |
import javax.annotation.PostConstruct; | |
import javax.annotation.PreDestroy; | |
import javax.annotation.Resource; | |
import javax.ejb.Lock; | |
import javax.ejb.LockType; | |
import javax.ejb.Singleton; | |
import javax.ejb.Startup; | |
import javax.jms.Connection; | |
import javax.jms.ConnectionFactory; | |
import javax.jms.JMSException; | |
import javax.jms.MessageProducer; | |
import javax.jms.Queue; | |
import javax.jms.Session; | |
import javax.jms.TextMessage; | |
import com.e.test.service.first.api.SendMessage; | |
@Singleton | |
@Startup | |
public class SendMessageService implements SendMessage { | |
@Resource(mappedName = "java:/ConnectionFactory") | |
private ConnectionFactory connectionFactory; | |
@Resource(mappedName = "java:/queue/test") | |
private Queue queue; | |
private Connection connection; | |
private Session session; | |
private MessageProducer messageProducer; | |
@PostConstruct | |
public void onStartup() throws JMSException{ | |
connection = this.connectionFactory.createConnection(); | |
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); | |
messageProducer = session.createProducer(this.queue); | |
} | |
@PreDestroy | |
public void onShutdown() throws JMSException{ | |
messageProducer.close(); | |
session.close(); | |
connection.close(); | |
} | |
@Override | |
@Lock(LockType.READ) | |
public void sendMessage(String text) { | |
try { | |
TextMessage message = session.createTextMessage(); | |
message.setText(text); | |
messageProducer.send(message); | |
System.out.println("----> W: "+text); | |
} catch (Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment