0

我有一个附加到请求对象的 JMS 对象,并且在 doPost() 方法中,正在调用对象的 get 方法来获取当前主题数据,这些数据将连续发送给客户端作为响应。

同时在另一个用户请求中,我在 doPost() 方法中看不到被调用的 get 消息,或者更确切地说,正在从调用中接收空/空字符串。

如何使该方法响应并发请求/用户。

关于调试:在 eclipse 中调试时,我有时会看到两个线程交替接收 getMessage 数据。

<jms:listener-container connection-factory="connectionFactory" task-executor="jmsTaskExecutor" destination-type="topic" concurrency="5">    
    <jms:listener destination="abc.topic" ref="abc" method="receive" />     
</jms:listener-container>

<bean name="jmsTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="2"/>
    <property name="maxPoolSize" value="50"/>       
    <property name="threadNamePrefix" value="some-queue-thread"/>
</bean>

<bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory"/>
    <property name="pubSubDomain" value="true"/>
</bean>


@Component("abc")
public class abc {

private String msg;

public synchronized void receive(String msg){       
    this.msg = msg;     
}


public synchronized String getMessage(){        
    return msg;     
}
}

@Component
@Controller
public class ForwardController extends ServletForwardingController
{   
@Autowired
abc topicObject;

@Override   
@RequestMapping("/xyzPath")
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {       
        request.setAttribute("autowired", topicObject);
        request.getRequestDispatcher("/xyz").forward(request, response);
    }        
return null;
}   

@WebServlet("/xyz")
public class xyz extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {

abc topicObject =  request.getAttribute("autowired");

while(true){        
    System.out.println("start"+Thread.currentThread.getId());
    String msg = topicObject.getMessage();
    response.getWriter.write(msg);
    System.out.println("stop"+Thread.currentThread.getId());
  }
 }
}

同时调用topicObject.getMessage()的正确方法是什么

4

1 回答 1

0

删除 @Async 注释。我不确定你打算做什么,但它没有这样做。

Javadoc

但是,返回类型被限制为voidor Future

并来自Spring 框架文档

可以在方法上提供 @Async 注释,以便异步调用该方法。换句话说,调用者将在调用时立即返回,并且该方法的实际执行将发生在已提交给 Spring TaskExecutor 的任务中。

换句话说,使用@Async,代码不会立即执行,而是稍后在另一个线程上执行,但它会立即返回。因此,对于您的getMessage,您提供的返回类型不受支持并导致未定义的行为(在您的情况下甚至是随机的)。

对于该receive方法,这也不是您想要的,因为它会将分配推迟到message.

解决方案:删除两个@Async 注释,并创建这两个方法synchronized,以便正确发布对message变量的更改,使其在所有线程中可见。

于 2015-01-09T06:45:17.670 回答