前面用java简单对rabbitmq进行了学习,但rabbitmq的功能远非如此,配合Spring或Springboot进行开发,才是java工程师做的工作,下面直接进行实战:
一、创建SSM项目
PS初期web项目下载地址(单纯的web,用于练习):
https://download.csdn.net/download/shenhaiyushitiaoyu/10810264
项目名:RabbitMQWeb
SSM(未包含RabbitMQ)的目录结构为:
以下是文件内容:
- applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name="location" value="classpath:database.properties"></property>
</bean>
<!-- 定义数据源dataSource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 使用JNDI方式 -->
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" >
<property name="jndiName" value="java:comp/env/jdbc/house"></property>
</bean> -->
<!-- 定义会话工厂sessionFactory -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 定义会话模板sqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype" >
<constructor-arg name="sqlSessionFactory" ref="sessionFactory" />
</bean>
</beans>
- database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/house?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
- log4j.properties
#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
# 1. DEBUG (the least serious)
# 2. INFO
# 3. WARN
# 4. ERROR
# 5. FATAL (the most serious)
# Set root logger level to WARN and append to stdout
#
log4j.rootLogger=DEBUG, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=logs/syslog.log
log4j.appender.R.DatePattern='.'yyyy-MM-dd
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy/MM/dd HH\:mm\:ss} [%p] [%t] %c.%M(%F\:%L) - %m%n
log4j.logger.noModule=FATAL
log4j.logger.com.opensymphony.xwork2=ERROR
log4j.logger.org.apache.struts2=ERROR
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 设置相关信息,需放在最前面 -->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 设置别名 -->
<typeAliases>
</typeAliases>
<!-- 管理映射文件 -->
<mappers>
</mappers>
</configuration>
- springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- BeanNameUrlHandlerMapping 将URL与controller进行映射 -->
<!-- <bean name="/login" class="controller.LoginController"> </bean> -->
<!-- DefaultAnnotationHandlerMapping 将URL与controller进行映射 -->
<context:component-scan base-package="test" />
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 静态资源文件进行处理,防止在访问图片、js、css文件时作为请求进行拦截 -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- <property name="maxUploadSize" value="2048000"></property> -->
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize">
<value>102400000</value>
</property>
<property name="maxInMemorySize">
<value>10240000</value>
</property>
</bean>
</beans>
为减少练习时间,可以先下载这个web demo(这样就可以直接在web基础上练习不需要搭建MVC项目浪费时间):
https://download.csdn.net/download/shenhaiyushitiaoyu/10810264
二、创建生产者和消费者:
注:本例是用direct交换器练习
- 消费者:MessageConsumer
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
public class MessageConsumer implements MessageListener {
private Logger logger = Logger.getLogger(MessageConsumer.class);
@Override
public void onMessage(Message message) {
logger.info("消费者和生产者项目---consumer receive message------->: "+message);
}
}
- 生产者:MessageProducer
import java.io.IOException;
import javax.annotation.Resource;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
@Service
public class MessageProducer {
@Resource(name="amqpTemplate")
private AmqpTemplate amqpTemplate;
public void sendMessage(Object message) throws IOException {
amqpTemplate.convertAndSend("queueTestKey", message); //queueTestKey:路由键 名称
}
}
- 配置文件:
1-创建spring-rabbitmq.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit-1.2.xsd">
<!--配置connection-factory,指定连接rabbit server参数 -->
<rabbit:connection-factory id="connectionFactory"
username="guest" password="guest" host="localhost" port="5672" />
<!--通过指定下面的admin信息,当前producer中的exchange和queue会在rabbitmq服务器上自动生成 -->
<rabbit:admin id="connectAdmin" connection-factory="connectionFactory" />
<!--定义queue -->
<rabbit:queue name="queueTest" durable="true" auto-delete="false"
exclusive="false" declared-by="connectAdmin" />
<!-- 定义direct exchange,绑定queueTest -->
<rabbit:direct-exchange name="exchangeTest" durable="true" auto-delete="false" declared-by="connectAdmin">
<rabbit:bindings>
<rabbit:binding queue="queueTest" key="queueTestKey"></rabbit:binding>
</rabbit:bindings>
</rabbit:direct-exchange>
<!--定义rabbit template用于数据的接收和发送 -->
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" exchange="exchangeTest" />
<!--消息接收者 com.consumer.MessageConsumer这个需要根据实际情况改过来-->
<bean id="messageReceiver" class="com.consumer.MessageConsumer"></bean>
<!-- queue litener 观察 监听模式 当有消息到达时会通知监听在对应的队列上的监听对象 -->
<rabbit:listener-container connection-factory="connectionFactory">
<rabbit:listener queues="queueTest" ref="messageReceiver" />
</rabbit:listener-container>
<!-- 其他的生产者,消费者,往下继续添加即可 -->
</beans>
- applicationContext.xml文件添加内容:
<!-- 导入rabbit.xml文件 -->
<import resource="classpath:spring-rabbitmq.xml"/>
图示:
- 编写测试controller:
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.producer.MessageProducer;
@Controller
@RequestMapping("test")
public class ReceiveRequestController {
@Autowired
private MessageProducer producer;
@RequestMapping("test")
public void test(){
try {
producer.sendMessage("测试进来啦啊 啊啊 啊");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
把项目添加到comcat中,启动后,浏览器输入:
http://localhost:8080/RabbitMQWeb/test/test
可以看到效果为:
至此已完成相关配置。只要懂得直接交换器的使用 其他两个交换器和其他的消费者,生产者就知道如何使用了。目前我的项目目录为:
demo下载地址:
https://download.csdn.net/download/shenhaiyushitiaoyu/10846118
下一篇我们将介绍两个系统间的通信,两个系统通信后,就可以对目前的大型项目进行拆分,做集群,分布式就很有帮助了。