How to do it...

Take the following steps to complete this recipe:

  1. First, we create a User POJO:
public class User implements Serializable{

private Long id;
private String name;

public User(long id, String name){
this.id = id;
this.name = name;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
  1. Then, we create a message sender:
@Stateless
public class Sender {

@Inject
private JMSContext context;

@Resource(lookup = "jms/JmsQueue")
private Destination queue;

public void send(User user){
context.createProducer()
.setDeliveryMode(DeliveryMode.PERSISTENT)
.setDisableMessageID(true)
.setDisableMessageTimestamp(true)
.send(queue, user);
}

}
  1. Now, we create a message consumer. This is our MDB:
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup",
propertyValue = "jms/JmsQueue"),
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue")
})
public class Consumer implements MessageListener{

@Override
public void onMessage(Message msg) {
try {
User user = msg.getBody(User.class);
System.out.println("User: " + user);
} catch (JMSException ex) {
System.err.println(ex.getMessage());
}
}

}
  1. Finally, we create an endpoint just to send a mock user to the queue:
@Stateless
@Path("mdbService")
public class MDBService {

@Inject
private Sender sender;

public void mdbService(@Suspended AsyncResponse response){
long id = new Date().getTime();
sender.send(new User(id, "User " + id));
response.resume("Message sent to the queue");
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.40.43