Dynamic Routing key on RabbitListener Annotation - spring

I need to create a queue linked to Direct Exchange for every user who has logged in to the application. The basement routing will be 'user_' + userId.
That is, every time I receive a message through the user management queue that a user is logged on. Instantiate a bean with scope 'prototype' that contains a method annotated with RabbitListener to declare its queue. To this bean, I passed the userId to be able to configure the name of the queue and routingKey. But I can not access this instance variable in the Spel expression due to a circular reference error.
Here I put the bean with which declares the queue:
#Component("usersHandler")
#Scope(value = "prototype")
public class UsersHandler {
private static Logger logger = LoggerFactory.getLogger(UsersHandler.class);
private Long userId;
public UsersHandler(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#RabbitListener(bindings
= #QueueBinding(
value = #Queue(
value = "#{'queue_'.concat(usersHandler.userId)}",
durable = "false",
autoDelete = "true",
arguments = {
#Argument(
name = "x-message-ttl",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-message-ttl']}",
type = "java.lang.Integer"
)
,
#Argument(
name = "x-expires",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-expires']}",
type = "java.lang.Integer"
)
,
#Argument(
name = "x-dead-letter-exchange",
value = "#{rabbitCustomProperties.directExchange.queueArguments['x-dead-letter-exchange']}",
type = "java.lang.String"
)
}
),
exchange = #Exchange(
value = "#{rabbitCustomProperties.directExchange.name}",
type = ExchangeTypes.DIRECT,
durable = "#{rabbitCustomProperties.directExchange.durable}",
autoDelete = "#{rabbitCustomProperties.directExchange.autoDelete}",
arguments = {
#Argument(
name = "alternate-exchange",
value = "#{rabbitCustomProperties.directExchange.arguments['alternate-exchange']}",
type = "java.lang.String"
)
}
),
key = "#{'user_'.concat(usersHandler.userId)}")
)
public void handleMessage(#Payload Notification notification) {
logger.info("Notification Received : " + notification);
}
}
This is the other bean in charge of creating as many UserHandler as users have logged in:
#Component("adminHandler")
public class AdminHandler implements UsersManadgementVisitor {
#Autowired
private ApplicationContext appCtx;
private Map<Long, UsersHandler> handlers = new HashMap<Long, UsersHandler>();
private static Logger logger = LoggerFactory.getLogger(AdminHandler.class);
#RabbitListener(queues="#{rabbitCustomProperties.adminExchange.queues['users'].name}")
public void handleMessage(#Payload UsersManadgementMessage message) {
logger.info("Message -> " + message);
message.getType().accept(this, message.getId());
}
#Override
public void visitUserConnected(Long idUser) {
logger.info("Declare new queue for user: " + idUser );
UsersHandler userHandler = appCtx.getBean(UsersHandler.class, idUser);
handlers.put(idUser, userHandler);
}
#Override
public void visitUserDisconnected(Long idUser) {
logger.info("Remove queue for user: " + idUser );
handlers.remove(idUser);
}
}
My question is this:
How can I make the variable userId available in the evaluation context of the SpEL expressions?

You could use a ThreadLocal and the T operator...
#SpringBootApplication
public class So43717710Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43717710Application.class, args);
UserHolder.setUser("someUser");
context.getBean(Listener.class);
UserHolder.clearUser();
context.getBean(RabbitTemplate.class).convertAndSend("foo", "user_someUser", "bar");
Thread.sleep(5000);
context.close();
}
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Listener listener() {
return new Listener();
}
public static class Listener {
#RabbitListener(bindings = #QueueBinding(value = #Queue("#{'queue_' + T(com.example.UserHolder).getUser()}"),
exchange = #Exchange(value = "foo"),
key = "#{'user_' + T(com.example.UserHolder).getUser()}"))
public void listen(String in) {
System.out.println(in);
}
}
}
public class UserHolder {
private static final ThreadLocal<String> user = new ThreadLocal<String>();
public static void setUser(String userId) {
user.set(userId);
}
public static String getUser() {
return user.get();
}
public static void clearUser() {
user.remove();
}
}
If the ThreadLocal is in a #Bean you can use a bean reference...
#SpringBootApplication
public class So43717710Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(So43717710Application.class, args);
UserHolder.setUser("someUser");
context.getBean(Listener.class);
UserHolder.clearUser();
context.getBean(RabbitTemplate.class).convertAndSend("foo", "user_someUser", "bar");
Thread.sleep(5000);
context.close();
}
#Bean
public UserHolder holder() {
return new UserHolder();
}
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public Listener listener() {
return new Listener();
}
public static class Listener {
#RabbitListener(bindings = #QueueBinding(value = #Queue("#{'queue_' + #holder.user}"),
exchange = #Exchange(value = "foo"),
key = "#{'user_' + #holder.user}"))
public void listen(String in) {
System.out.println(in);
}
}
}

Related

validate raw message against schema for method annotated with jmslistener

I have a need to apply some pre-checks and common steps on the all the jms listeners like validating the raw message against a schema (JSON schema). Example -
#Component
public class MyService {
#JmsListener(destination = "myDestination")
public void processOrder(Order order) { ... }
}
Now, before the spring converts the Message from the queue to Order, I need to do the following -
log the original message with headers into a custom logger.
validate the json message (text message) against a json schema (lets assume I have only one schema here for the simplicity)
If schema validation fail, log the error and throw exception
If schema validation passes, continue to control to spring to do the conversion and continue with the process order method.
Does the spring JMS architecture provides any way to inject the above need?
I know AOP crosses the mind, but I am not sure will it work with #JmsListener.
A rather simple technique would be to set autoStartup to false on the listener container factory.
Then, use the JmsListenerEndpointRegistry bean to get the listener container.
Then getMessageListener(), wrap it in an AOP proxy and setMessageListener().
Then start the container.
There might be a more elegant way, but I think you'd have to get into the guts of the listener creation code, which is quite involved.
EDIT
Example with Spring Boot:
#SpringBootApplication
public class So49682934Application {
private final Logger logger = LoggerFactory.getLogger(getClass());
public static void main(String[] args) {
SpringApplication.run(So49682934Application.class, args);
}
#JmsListener(id = "listener1", destination = "so49682934")
public void listen(Foo foo) {
logger.info(foo.toString());
}
#Bean
public ApplicationRunner runner(JmsListenerEndpointRegistry registry, JmsTemplate template) {
return args -> {
DefaultMessageListenerContainer container =
(DefaultMessageListenerContainer) registry.getListenerContainer("listener1");
Object listener = container.getMessageListener();
ProxyFactory pf = new ProxyFactory(listener);
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(new MyJmsInterceptor());
advisor.addMethodName("onMessage");
pf.addAdvisor(advisor);
container.setMessageListener(pf.getProxy());
registry.start();
Thread.sleep(5_000);
Foo foo = new Foo("baz");
template.convertAndSend("so49682934", foo);
};
}
#Bean
public MessageConverter converter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("typeId");
return converter;
}
public static class MyJmsInterceptor implements MethodInterceptor {
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Message message = (Message) invocation.getArguments()[0];
logger.info(message.toString());
// validate
return invocation.proceed();
}
}
public static class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return "Foo [bar=" + this.bar + "]";
}
}
}
and
spring.jms.listener.auto-startup=false
and
m2018-04-06 11:42:04.859 INFO 59745 --- [enerContainer-1] e.So49682934Application$MyJmsInterceptor : ActiveMQTextMessage {commandId = 5, responseRequired = true, messageId = ID:gollum.local-60138-1523029319662-4:2:1:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:gollum.local-60138-1523029319662-4:2:1:1, destination = queue://so49682934, transactionId = null, expiration = 0, timestamp = 1523029324849, arrival = 0, brokerInTime = 1523029324849, brokerOutTime = 1523029324853, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 1050, properties = {typeId=com.example.So49682934Application$Foo}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = {"bar":"baz"}}
2018-04-06 11:42:04.882 INFO 59745 --- [enerContainer-1] ication$$EnhancerBySpringCGLIB$$e29327b8 : Foo [bar=baz]
EDIT2
Here's how to do it via infrastructure...
#SpringBootApplication
#EnableJms
public class So496829341Application {
private final Logger logger = LoggerFactory.getLogger(getClass());
public static void main(String[] args) {
SpringApplication.run(So496829341Application.class, args);
}
#JmsListener(id = "listen1", destination="so496829341")
public void listen(Foo foo) {
logger.info(foo.toString());
}
#Bean
public ApplicationRunner runner(JmsTemplate template) {
return args -> {
Thread.sleep(5_000);
template.convertAndSend("so496829341", new Foo("baz"));
};
}
#Bean
public MessageConverter converter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("typeId");
return converter;
}
#Bean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
public static JmsListenerAnnotationBeanPostProcessor bpp() {
return new JmsListenerAnnotationBeanPostProcessor() {
#Override
protected MethodJmsListenerEndpoint createMethodJmsListenerEndpoint() {
return new MethodJmsListenerEndpoint() {
#Override
protected MessagingMessageListenerAdapter createMessageListener(
MessageListenerContainer container) {
MessagingMessageListenerAdapter listener = super.createMessageListener(container);
ProxyFactory pf = new ProxyFactory(listener);
pf.setProxyTargetClass(true);
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(new MyJmsInterceptor());
advisor.addMethodName("onMessage");
pf.addAdvisor(advisor);
return (MessagingMessageListenerAdapter) pf.getProxy();
}
};
}
};
}
public static class MyJmsInterceptor implements MethodInterceptor {
private final Logger logger = LoggerFactory.getLogger(getClass());
#Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Message message = (Message) invocation.getArguments()[0];
logger.info(message.toString());
// validate
return invocation.proceed();
}
}
public static class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return "Foo [bar=" + this.bar + "]";
}
}
}
Note: the BPP must be static and #EnableJms is required since the presence of this BPP disables boot's.
2018-04-06 13:44:41.607 INFO 82669 --- [enerContainer-1] .So496829341Application$MyJmsInterceptor : ActiveMQTextMessage {commandId = 5, responseRequired = true, messageId = ID:gollum.local-63685-1523036676402-4:2:1:1:1, originalDestination = null, originalTransactionId = null, producerId = ID:gollum.local-63685-1523036676402-4:2:1:1, destination = queue://so496829341, transactionId = null, expiration = 0, timestamp = 1523036681598, arrival = 0, brokerInTime = 1523036681598, brokerOutTime = 1523036681602, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = null, marshalledProperties = null, dataStructure = null, redeliveryCounter = 0, size = 1050, properties = {typeId=com.example.So496829341Application$Foo}, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = {"bar":"baz"}}
2018-04-06 13:44:41.634 INFO 82669 --- [enerContainer-1] ication$$EnhancerBySpringCGLIB$$9ff4b13f : Foo [bar=baz]
EDIT3
Avoiding AOP...
#SpringBootApplication
#EnableJms
public class So496829341Application {
private final Logger logger = LoggerFactory.getLogger(getClass());
public static void main(String[] args) {
SpringApplication.run(So496829341Application.class, args);
}
#JmsListener(id = "listen1", destination="so496829341")
public void listen(Foo foo) {
logger.info(foo.toString());
}
#Bean
public ApplicationRunner runner(JmsTemplate template) {
return args -> {
Thread.sleep(5_000);
template.convertAndSend("so496829341", new Foo("baz"));
};
}
#Bean
public MessageConverter converter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("typeId");
return converter;
}
#Bean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
public static JmsListenerAnnotationBeanPostProcessor bpp() {
return new JmsListenerAnnotationBeanPostProcessor() {
#Override
protected MethodJmsListenerEndpoint createMethodJmsListenerEndpoint() {
return new MethodJmsListenerEndpoint() {
#Override
protected MessagingMessageListenerAdapter createMessageListener(
MessageListenerContainer container) {
final MessagingMessageListenerAdapter listener = super.createMessageListener(container);
return new MessagingMessageListenerAdapter() {
#Override
public void onMessage(Message jmsMessage, Session session) throws JMSException {
logger.info(jmsMessage.toString());
// validate
listener.onMessage(jmsMessage, session);
}
};
}
};
}
};
}
public static class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return "Foo [bar=" + this.bar + "]";
}
}
}
EDIT4
To access other annotations on the listener method, it can be done, but reflection is needed to get a reference to the Method...
#JmsListener(id = "listen1", destination="so496829341")
#Schema("foo.bar")
public void listen(Foo foo) {
logger.info(foo.toString());
}
#Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Inherited
#Documented
public #interface Schema {
String value();
}
#Bean(JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME)
public static JmsListenerAnnotationBeanPostProcessor bpp() {
return new JmsListenerAnnotationBeanPostProcessor() {
#Override
protected MethodJmsListenerEndpoint createMethodJmsListenerEndpoint() {
return new MethodJmsListenerEndpoint() {
#Override
protected MessagingMessageListenerAdapter createMessageListener(
MessageListenerContainer container) {
final MessagingMessageListenerAdapter listener = super.createMessageListener(container);
InvocableHandlerMethod handlerMethod =
(InvocableHandlerMethod) new DirectFieldAccessor(listener)
.getPropertyValue("handlerMethod");
final Schema schema = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), Schema.class);
return new MessagingMessageListenerAdapter() {
#Override
public void onMessage(Message jmsMessage, Session session) throws JMSException {
logger.info(jmsMessage.toString());
logger.info(schema.value());
// validate
listener.onMessage(jmsMessage, session);
}
};
}
};
}
};
}

how to add entity listener programmable in Hibernate JPA

I use spring, hibernate, jpa2.1.
as follow:
#Entity
#EntityListeners(DemoListener.class)
public class Demo {
#Id
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
public class DemoListener {
#PersistenceContext
private EntityManager entityManager;
#PrePersist
public void prePersist(Demo demo){
}
}
the example works well, when I want to add more listener, I must modify the Demo entity, but the Demo is in other jar,I don't want to use the XML configuration, is there some way like this:
...addListener(Demo.class, new DemoListener());
...addListener(Demo.class, new OtherDemoListener());
base on hibernate-orm docs and hibernate-tutorials:
/**
* #param <T> one of {#link EventType#baseListenerInterface()}
* #see org.hibernate.event.service.spi.EventListenerRegistry
*/
public interface JpaEventListenerRegistry<T> {
/**
* add listener for entity class
*
* #param entityClass can't be null
* #param listener can't be null
*/
void addListener(Class<?> entityClass, T listener);
}
public class JpaEventListenerRegistryImpl implements JpaEventListenerRegistry<Object> {
private Logger logger = LoggerFactory.getLogger(getClass());
private EventListenerRegistry eventListenerRegistry;
private Map<EventType, JpaEventListenerRegistry> listeners = new HashMap<EventType, JpaEventListenerRegistry>();
public JpaEventListenerRegistryImpl(EventListenerRegistry eventListenerRegistry) {
this.eventListenerRegistry = eventListenerRegistry;
initDefault();
}
private void initDefault() {
listeners.put(EventType.PRE_INSERT, new DomainPreInsertEventListener());
listeners.put(EventType.POST_INSERT, new DomainPostInsertEventListener());
for (Map.Entry<EventType, JpaEventListenerRegistry> entry : listeners.entrySet()) {
eventListenerRegistry.appendListeners(entry.getKey(), entry.getValue());
}
}
#SuppressWarnings("unchecked")
public void addListener(Class<?> entityClass, Object listener) {
logger.info("add listener {} for entity {}", listener, entityClass.getName());
for (EventType eventType : EventType.values()) {
Class<?> listenerInterface = eventType.baseListenerInterface();
if (listenerInterface.isAssignableFrom(listener.getClass())) {
JpaEventListenerRegistry registry = listeners.get(eventType);
if (registry == null) {
logger.warn("the event type {} for listener {} is not supported", eventType, listener);
} else {
registry.addListener(entityClass, listener);
}
}
}
}
public static class Abstract<T> implements JpaEventListenerRegistry<T> {
private Logger logger = LoggerFactory.getLogger(getClass());
private Map<Class<?>, List<T>> listeners = new HashMap<Class<?>, List<T>>();
public void addListener(Class<?> entityClass, T listener) {
logger.info("add listener {} for entity {}", listener, entityClass.getName());
List<T> listeners = this.listeners.get(entityClass);
if (listeners == null) {
listeners = new ArrayList<T>();
this.listeners.put(entityClass, listeners);
}
listeners.add(listener);
}
List<T> findListener(Class<?> entityClass) {
for (Map.Entry<Class<?>, List<T>> entry : listeners.entrySet()) {
if (entry.getKey().isAssignableFrom(entityClass)) {
return entry.getValue();
}
}
return null;
}
}
public static class DomainPreInsertEventListener extends Abstract<PreInsertEventListener> implements PreInsertEventListener {
public boolean onPreInsert(PreInsertEvent event) {
return onPreInsert(event, findListener(event.getEntity().getClass()));
}
private boolean onPreInsert(PreInsertEvent event, List<PreInsertEventListener> listeners) {
if (listeners == null) return false;
for (PreInsertEventListener listener : listeners) {
if (listener.onPreInsert(event)) return true;
}
return false;
}
}
public static class DomainPostInsertEventListener extends Abstract<PostInsertEventListener> implements PostInsertEventListener {
public void onPostInsert(PostInsertEvent event) {
onPostInsert(event, findListener(event.getEntity().getClass()));
}
private void onPostInsert(PostInsertEvent event, List<PostInsertEventListener> listeners) {
if (listeners == null) return;
for (PostInsertEventListener listener : listeners) {
listener.onPostInsert(event);
}
}
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
}
}
public class EntityManagerIllustrationTest extends TestCase {
private EntityManagerFactory entityManagerFactory;
#Override
protected void setUp() throws Exception {
// like discussed with regards to SessionFactory, an EntityManagerFactory is set up once for an application
// IMPORTANT: notice how the name here matches the name we gave the persistence-unit in persistence.xml!
entityManagerFactory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
SessionFactoryImplementor sessionFactory = entityManagerFactory.unwrap(SessionFactoryImplementor.class);
EventListenerRegistry eventListenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
JpaEventListenerRegistryImpl jpaEventListenerRegistry = new JpaEventListenerRegistryImpl(eventListenerRegistry);
jpaEventListenerRegistry.addListener(EventListener.class, new JpaEventListener());
}
private static class JpaEventListener implements PreInsertEventListener, PostInsertEventListener {
public boolean onPreInsert(PreInsertEvent event) {
Event entity = (Event) event.getEntity();
System.out.println("onPreInsert:" + entity);
return false;
}
public void onPostInsert(PostInsertEvent event) {
Event entity = (Event) event.getEntity();
System.out.println("onPostInsert:" + entity);
}
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
}
#Override
protected void tearDown() throws Exception {
entityManagerFactory.close();
}
public void testBasicUsage() {
// create a couple of events...
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(new Event("Our very first event!", new Date()));
// entityManager.persist(new Event("A follow up event", new Date()));
entityManager.getTransaction().commit();
entityManager.close();
// now lets pull events from the database and list them
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
List<Event> result = entityManager.createQuery("from Event", Event.class).getResultList();
for (Event event : result) {
System.out.println("Event (" + event.getDate() + ") : " + event.getTitle());
}
entityManager.getTransaction().commit();
entityManager.close();
}
}

Spring Mvc with Thread

Hi My thread class is showing null pointer exception please help me to resolve
#Component
public class AlertsToProfile extends Thread {
public final Map<Integer, List<String>> userMessages = Collections.synchronizedMap(new HashMap<Integer, List<String>>());
#Autowired
ProfileDAO profileDAO;
private String categoryType;
private String dataMessage;
public String getCategoryType() {
return categoryType;
}
public void setCategoryType(String categoryType) {
this.categoryType = categoryType;
}
public String getDataMessage() {
return dataMessage;
}
public void setDataMessage(String dataMessage) {
this.dataMessage = dataMessage;
}
public void run() {
String category=getCategoryType();
String data= getDataMessage();
List<Profile> all = profileDAO.findAll();
if (all != null) {
if (category == "All" || category.equalsIgnoreCase("All")) {
for (Profile profile : all) {
List<String> list = userMessages.get(profile.getId());
if (list == null ) {
ArrayList<String> strings = new ArrayList<String>();
strings.add(data);
userMessages.put(profile.getId(), strings);
} else {
list.add(data);
}
}
}
}
}
and my service method is as follows
#Service
public class NoteManager
{
#Autowired AlertsToProfile alertsToProfile;
public void addNote(String type, String message, String category) {
alertsToProfile.setCategoryType(category);
String data = type + "," + message;
alertsToProfile.setDataMessage(data);
alertsToProfile.start();
System.out.println("addNotes is done");
}
But when i call start() method am getting null pointer exception please help me. I am new to spring with thread concept
It pretty obvious: you instantiate your thread directly, as opposed to letting spring create AlertsToProfile and auto wire your instance.
To fix this, create a Runnable around your run() method and embed that into a method, something like this:
public void startThread() {
new Thread(new Runnable() {
#Override
public void run() {
// your code in here
}}).start();
}
you will want to bind the Thread instance to a field in AlertsToProfile in order to avoid leaks and stop the thread when you're done.

Spring 4.0.5 websockt integration apollo with the exception "Message broker is not active"

For a project,i want to switch the project from simple broker to full-feature broker(like rabiitmq, apollo).
the exception stack:
Caused by: org.springframework.messaging.MessageDeliveryException: Message broker is not active.
at org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler.handleMessageInternal(StompBrokerRelayMessageHandler.java:392)
at org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler.handleMessage(AbstractBrokerMessageHandler.java:177)
at org.springframework.messaging.support.ExecutorSubscribableChannel.sendInternal(ExecutorSubscribableChannel.java:64)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:116)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:98)
at org.springframework.messaging.simp.SimpMessagingTemplate.doSend(SimpMessagingTemplate.java:125)
at org.springframework.messaging.simp.SimpMessagingTemplate.doSend(SimpMessagingTemplate.java:48)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:94)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.convertAndSend(AbstractMessageSendingTemplate.java:144)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.convertAndSend(AbstractMessageSendingTemplate.java:112)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.convertAndSend(AbstractMessageSendingTemplate.java:107)
at cn.clickmed.cmcp.websocket.plain.util.WebSocketUtil.sendMessage(WebSocketUtil.java:61)
at cn.clickmed.cmcp.websocket.plain.util.WebSocketUtil.sendMessage(WebSocketUtil.java:65)
at cn.clickmed.cmcp.websocket.plain.entity.WebSocketEntity.postPersist(WebSocketEntity.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
here is the config code:
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
for(String mapping : WebSocketConstant.WEBSOCKETTYPE.keySet()) {
registry.addEndpoint(mapping).withSockJS();
}
}
#Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/websocket");
// registry.enableSimpleBroker("/topic");
registry.enableStompBrokerRelay("/topic","/queue").setRelayHost("localhost").setRelayPort(61613).setSystemHeartbeatReceiveInterval(2000).setSystemHeartbeatSendInterval(2000);
// registry.setUserDestinationPrefix("/topic/");
}
#Bean
public Broker broker() throws Exception {
final Broker broker = new Broker();
// Configure STOMP over WebSockects connector
final AcceptingConnectorDTO ws = new AcceptingConnectorDTO();
ws.id = "ws";
ws.bind = "ws://localhost:61613";
ws.protocols.add( new StompDTO() );
// Create a topic with name 'test'
final TopicDTO topic = new TopicDTO();
topic.id = "todoListener";
// Create virtual host (based on localhost)
final VirtualHostDTO host = new VirtualHostDTO();
host.id = "localhost";
host.topics.add( topic );
host.host_names.add( "localhost" );
host.host_names.add( "127.0.0.1" );
host.auto_create_destinations = false;
// Create a web admin UI (REST) accessible at: http://localhost:61680/api/index.html#!/
final WebAdminDTO webadmin = new WebAdminDTO();
webadmin.bind = "http://localhost:61680";
// Create JMX instrumentation
final JmxDTO jmxService = new JmxDTO();
jmxService.enabled = true;
// Finally, glue all together inside broker configuration
final BrokerDTO config = new BrokerDTO();
config.connectors.add( ws );
config.virtual_hosts.add( host );
config.web_admins.add( webadmin );
config.services.add( jmxService );
broker.setConfig( config );
broker.setTmp( new File( System.getProperty( "java.io.tmpdir" ) ) );
broker.start( new Runnable() {
#Override
public void run() {
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:启动了");
}
} );
return broker;
}
}
send message code:
public class WebSocketUtil implements ILog{
public static Map<String, List<WebSocketSession>> webSocketSessionMap = new HashMap<String, List<WebSocketSession>>();
public static SimpMessagingTemplate simpMessagingTemplate = null;
public static void doSendMessage(String webSocketType) throws IOException {
if(WebSocketUtil.webSocketSessionMap.get(webSocketType) != null) {
String msg = "";
if(WebSocketConstant.WEBSOCKETTYPE_TODOLIST.equals(webSocketType)) {
msg = "change";
}
for(WebSocketSession webSocketSession :WebSocketUtil.webSocketSessionMap.get(webSocketType)) {
webSocketSession.sendMessage(new TextMessage(msg));
}
}
}
public static String getWebSocketType(String url) {
int length = url.indexOf("/cmcp/");
String theUrl = url.substring(length+5);
if(theUrl.startsWith(WebSocketConstant.COMPATIBLEMAPPING)) {
String [] arr = theUrl.split("/");
theUrl = "/"+arr[2];
}
if(!WebSocketConstant.WEBSOCKETTYPE.containsKey(theUrl)) {
logger.error("please config the websocketConstant !!!!");
throw new RuntimeException();
}
String theType = WebSocketConstant.WEBSOCKETTYPE.get(theUrl);
return theType;
}
public synchronized static void initSimpMessagingTemplate() {
if(simpMessagingTemplate == null) {
simpMessagingTemplate = SpringUtil.getBeanByName("brokerMessagingTemplate");
}
}
public static void sendMessage(String topic, String message) {
if(simpMessagingTemplate == null) {
initSimpMessagingTemplate();
}
simpMessagingTemplate.convertAndSend("/topic"+topic, message);
}
public static void sendMessage(String topic) {
sendMessage(topic,"change");
}
}
this is the trigger entity:
#MappedSuperclass
public class WebSocketEntity extends CommonEntity {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
#PostPersist
public void postPersist() throws IOException{
if(this instanceof TodoEntity) {
WebSocketUtil.sendMessage(WebSocketConstant.WEBSOCKETTYPE_TODOLIST_MAPPING);
}
}
#PostRemove
public void postRemove() throws IOException{
if(this instanceof TodoEntity) {
WebSocketUtil.sendMessage(WebSocketConstant.WEBSOCKETTYPE_TODOLIST_MAPPING);
}
}
}
please give me help! thanks!

HttpSession attribute getting removed abnormally after adding

*After I add a session attribute using
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
#RequestMapping(value="/minasidor/step1",method=RequestMethod.GET)
public ModelAndView step1(HttpServletRequest request,HttpSession session){
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: start");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [Start]");
ModelAndView mav=new ModelAndView("vz-new/mina-sidor/v-orderstep1");
LoginBean user = (LoginBean) WebUtils.getSessionAttribute(request, VBWebConstants.SESSION_USER);
mav.addObject("submenu",3);
if(!checkOrderLifeCycle()){
mav.addObject("orderNotAllowed", false);
return mav;
}
try{
String orderValue = "";
orderValue = InMemoryCache.getCaProperty(PropertyEnum.MIN_ORDER_VALUE.getDatabasekey());
int minimumOrderValue = CawebUtil.isInt(orderValue);
CpSellerDetails sellerDetails=vbOrderService.getStep1Data(user.getGrp_seller_id(),user.getCatalogue_id());
if(sellerDetails != null){
mav.addObject("productlist",sellerDetails.getSellerList());
mav.addObject("totalValue",sellerDetails.getTotalOrderValue());
mav.addObject("allowedfororder",sellerDetails.getTotalOrderValue() > minimumOrderValue);
// mav addobject add discount details Discount Object ArrayList
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,"step1");
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_BEAN,sellerDetails);
}else{
mav.addObject("allowedfororder",false);
WebUtils.setSessionAttribute(request, VBWebConstants.SESSION_ORDER_STEP_COMPLETED,null);
}
}catch(DataNotFoundException e){
logger.trace("Exception in retrieving data for step1",e);
if(logger.isDebugEnabled())logger.debug("[Order Step1 Exception]",e);
}
if(logger.isTraceEnabled())logger.trace("VbSellerController ::: step1 ::: end");
if(logger.isDebugEnabled())logger.debug("[Order Step1] [end]");
return mav;
}
Within this step1 method the VBWebConstants.SESSION_ORDER_BEAN session attribute is getting removed instantly after the step1() method finishes executing where as the other session attributes remains the same.When i debug the below Http Listener class
public class MyHttpSessionListener implements HttpSessionListener,HttpSessionAttributeListener {
public static final Logger logger = Logger.getLogger(MyHttpSessionListener.class);
public void sessionCreated(HttpSessionEvent se) {
//String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Session Created -------------- ");
Enumeration<String> sessionAttrs = session.getAttributeNames();
while (sessionAttrs.hasMoreElements()) {
String name = sessionAttrs.nextElement();
sbuilder.append("\n").append(" session created ").append(name);
}
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
sbuilder.append("\n").append("---------------------------------------------------- ").append("\n");
logger.debug(sbuilder.toString());
}
}
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
try{
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
logger.debug(" session destroyed " +ipAddr);
}catch (Exception e) {
}
}
}
public void attributeAdded(HttpSessionBindingEvent se) {
String ipAddr = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest().getRemoteAddr();
HttpSession session = se.getSession();
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute added -------------- from ").append(ipAddr);
sbuilder.append("\n").append(" session max inactive time "+ session.getMaxInactiveInterval());
sbuilder.append("\n").append(" session id "+ session.getId());
sbuilder.append("\n").append(" session attribute added "+ se.getName()).append(" = ").append(se.getValue());
sbuilder.append("\n").append(" session created time "+ CawebUtil.getTimeStampInString(new Timestamp(session.getCreationTime())));
}
}
public void attributeRemoved(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled() ){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute removed -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute removed "+ se.getName()).append(" = ").append(se.getValue());
}
}
public void attributeReplaced(HttpSessionBindingEvent se) {
if(logger.isDebugEnabled()){
StringBuilder sbuilder = new StringBuilder();
sbuilder.append("\n").append("----------- Attribute replaced -------------- from ");//.append(ipAddr);
sbuilder.append("\n").append(" session attribute "+ se.getName()).append(" = ").append(se.getValue());
}
}
}
I found that the session attribute is getting removed.Checked through the entire code I couldn't find what's the reason...???
Here is the CPSellerDetails class which i try to add to the session there are other 2 session attributes among which one is a string object and other is a bean.could it the size of the class that is the cause for session attribute being removed abnormally
public class CpSellerDetails implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4627284179051380310L;
private List<SellerProduct> sellerList ;
private float totalOrderValue ;
private VbCpInfoBean cpinfoBean;
private Integer orderno;
private float invoiceAmount;
private Date orderedDate;
private ArrayList<DiscountVO> discounts;
private Address billingInfo;
public VbCpInfoBean getCpInfoBean() {
return cpinfoBean;
}
public void setCpInfoBean(VbCpInfoBean infoBean) {
this.cpinfoBean = infoBean;
}
public List<SellerProduct> getSellerList() {
return sellerList;
}
public void setSellerList(List<SellerProduct> sellerList) {
this.sellerList = sellerList;
}
public float getTotalOrderValue() {
return totalOrderValue;
}
public void setTotalOrderValue(float totalOrderValue) {
this.totalOrderValue = totalOrderValue;
}
public float getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(float invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public Integer getOrderno() {
return orderno;
}
public void setOrderno(Integer orderno) {
this.orderno = orderno;
}
public Date getOrderedDate() {
return orderedDate;
}
public void setOrderedDate(Date orderedDate) {
this.orderedDate = orderedDate;
}
public ArrayList<DiscountVO> getDiscounts() {
return discounts;
}
public void setDiscounts(ArrayList<DiscountVO> discounts) {
this.discounts = discounts;
}
public Address getBillingInfo() {
return billingInfo;
}
public void setBillingInfo(Address billingInfo) {
this.billingInfo = billingInfo;
}
}*

Resources