自学这个地方,遇到了许多莫名其妙的错误,也是对自己搞了一整天的一个总结,免得后面又忘记。
(1)首先,发送消息的话应该有消息代理这里我们在spring中搭建消息代理使用ActiveMQ。
在http://activemq.apache.org 下载AcitveMQ,推荐5.9.0,版本不是最新的都可以(因为我首先下载最新版本的,你们懂得,版本太高,会出现一些jar包不匹配等问题),然后运行bin下的activemq.bat 启动。
测试是否成功启动的方法:http://127.0.0.1:8161/ 如果能打开,ok,成功启动。
此时消息代理就搭建好了。
(2)除了spring必须有的jar包外,项目所需的jar包:activemq-all-5.9.0.jar、xbean-spring-3.12.jar、spring-jms-3.2.7.RELEASE.jar (可根据自己项目来匹配版本)
(3)在xml中的配置
<amq:connectionFactory id="connectionFactory" brokerURL="tcp://localhost:61616"></amq:connectionFactory>
<bean id="queue" class="org.apache.activemq.command.ActiveMQQueue" c:_="user.queue"></bean>
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate" c:_-ref="connectionFactory"></bean>
<bean id="userHandler" class="com.coshine.jms.UserAlertHandler"></bean>
<jms:listener-container connection-factory="connectionFactory">
<jms:listener destination="user.alert.queue" ref="userHandler" method="handlerUserAlert"/>
</jms:listener-container>
xmlns:c="http://www.springframework.org/schema/c"
xmlns:jms="http://www.springframework.org/schema/jms"
xmlns:amq="http://activemq.apache.org/schema/core"
http://www.springframework.org/schema/jms
http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd
这两部分在对应位置搞一下
(4)具体代码
UserDTO:
public class UserDTO implements Serializable{
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
AlertService接口:
public interface AlertService {
void sendUserAlert(UserDTO user);
}
AlertServiceImpl:(jms发送消息)
@Component
public class AlertServiceImpl implements AlertService{
private JmsOperations jsmOperations;
@Autowired
public AlertServiceImpl(@Qualifier("jmsTemplate") JmsOperations jsmOperations) {
this.jsmOperations = jsmOperations;
}
@Override
public void sendUserAlert(final UserDTO user) {
System.out.println("这里是service");
jsmOperations.send("user.alert.queue", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createObjectMessage(user); //创建消息
}
});
}
}
UserAlertHandler:(使用监听器接收消息)对应的配置在xml中都有
public class UserAlertHandler {
public void handlerUserAlert(UserDTO user){
System.out.println("接收到的消息为:"+user.getUserName());
}
}
ActiveMQController:
@Controller
@RequestMapping("/activeMQ")
public class ActiveMQController {
@Autowired
private AlertService alertService;
@ResponseBody
@RequestMapping("/queue")
public String queueSender(UserDTO user){
try{
alertService.sendUserAlert(user);
return "success";
}catch(Exception e){
return "false";
}
}
}