springboot整合xxl-mq学习笔记
首先xxl-mq是大神xuxueli开发的一个消息中间件框架:
与springboot整合过程:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-mq-samples</artifactId>
<version>1.3.-SNAPSHOT</version>
</parent>
<modelVersion>4.0.</modelVersion>
<artifactId>xxl-mq-samples-springboot</artifactId>
<packaging>jar</packaging> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies> <!-- starter-web:spring-webmvc + autoconfigure + logback + yaml + tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- starter-test:junit + spring-test + mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <!-- freemarker-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency> <!-- xxl-mq-client -->
<dependency>
<groupId>com.xuxueli</groupId>
<artifactId>xxl-mq-client</artifactId>
<version>${parent.version}</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build> </project>
2 propeties
### web
server.port=
server.context-path=/ ### resources
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/ ### freemarker
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
spring.freemarker.request-context-attribute=request
spring.freemarker.settings.number_format=0.########## # xxl-mq, admin conf 这个配置时admin部署的位置
xxl.mq.admin.address=http://localhost:8080/xxl-mq-admin
### xxl-mq, access token
xxl.mq.accessToken=
index。html
<script src="${request.contextPath}/static/jquery/jquery.min.js"></script>
<body>
<input type="button" class="send" _type="" value="并行消费" />
<br><br>
<input type="button" class="send" _type="" value="串行消费" />
<br><br>
<input type="button" class="send" _type="" value="广播消息" />
<br><br>
<input type="button" class="send" _type="" value="延时消息:5分钟后执行" />
<br><br>
<input type="button" class="send" _type="" value="性能测试:批量发送10000条消息" />
<hr>
<div id="console"></div>
<script>
$(function(){
$(".send").click(function () {
var _type = $(this).attr("_type");
$.post( '${request.contextPath}/produce', {'type':_type}, function(data,status){
var temp = "<br>" + new Date().format("yyyy-MM-dd HH:mm:ss") + ": ";
temp += ("SUCCESS" == data)?('成功发送一条消息!'):data;
$("#console").prepend(temp);
});
});
});
// Format
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth()+, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+)/), //季度
"S" : this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$, (this.getFullYear()+"").substr( - RegExp.$.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$, (RegExp.$.length==) ? (o[k]) : ((""+ o[k]).substr((""+ o[k]).length)));
return fmt;
}
</script>
</body>
需要在juery下面引入:
日志管理配置:
logback。xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="true" scanPeriod="1 seconds"> <contextName>logback</contextName>
<property name="log.path" value="/data/applogs/xxl-mq/xxl-mq-samples-springboot.log"/> <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{} - %msg%n</pattern>
</encoder>
</appender> <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern>
</rollingPolicy>
<encoder>
<pattern>%date %level [%thread] %logger{} [%file : %line] %msg%n
</pattern>
</encoder>
</appender> <root level="info">
<appender-ref ref="console"/>
<appender-ref ref="file"/>
</root> </configuration>
配置XxlMqConf.java:
package com.xxl.mq.sample.springboot.conf; import com.xxl.mq.client.factory.impl.XxlMqSpringClientFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component; @Component
public class XxlMqConf { // ---------------------- param ---------------------- @Value("${xxl.mq.admin.address}")
private String adminAddress;
@Value("${xxl.mq.accessToken}")
private String accessToken; @Bean
public XxlMqSpringClientFactory getXxlMqConsumer(){ XxlMqSpringClientFactory xxlMqSpringClientFactory = new XxlMqSpringClientFactory();
xxlMqSpringClientFactory.setAdminAddress(adminAddress);
xxlMqSpringClientFactory.setAccessToken(accessToken); return xxlMqSpringClientFactory;
} }
controller 根据传入的参数进行设置:
import com.xxl.mq.client.message.XxlMqMessage;
import com.xxl.mq.client.producer.XxlMqProducer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.Calendar;
import java.util.Date; /**
* index controller
* @author xuxueli 2015-12-19 16:13:16
*/
@Controller
public class IndexController { @RequestMapping("/")
public String index(){
return "index";
} @RequestMapping("/produce")
@ResponseBody
public String produce(int type){ String topic = "topic_1";
String data = "时间戳:" + System.currentTimeMillis(); if (type == ) { /**
* 并行消费
*/
XxlMqProducer.produce(new XxlMqMessage(topic, data)); } else if (type == ) { /**
* 串行消费
*/
XxlMqProducer.produce(new XxlMqMessage(topic, data, 1L)); } else if (type == ) { /**
* 广播消费
*/
XxlMqProducer.broadcast(new XxlMqMessage(topic, data)); } else if (type == ) { Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, );
Date effectTime = calendar.getTime(); /**
* 延时消息
*/
XxlMqProducer.produce(new XxlMqMessage(topic, data, effectTime)); } else if (type == ) { int msgNum = ;
long start = System.currentTimeMillis();
for (int i = ; i < msgNum; i++) {
XxlMqProducer.produce(new XxlMqMessage("topic_1", "No:"+i));
}
long end = System.currentTimeMillis();
return "Cost = " + (end-start); } else {
return "Type Error.";
} return "SUCCESS";
} @ExceptionHandler({Exception.class})
public String exception(Exception e) {
e.printStackTrace();
return e.getMessage();
} }
对应的消费者:
import com.xxl.mq.client.consumer.IMqConsumer;
import com.xxl.mq.client.consumer.MqResult;
import com.xxl.mq.client.consumer.annotation.MqConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; /**
* Created by xuxueli on 16/8/28.
*/
@MqConsumer(topic = "topic_2")
@Service
public class Demo2MqComsumer implements IMqConsumer {
private Logger logger = LoggerFactory.getLogger(Demo2MqComsumer.class); @Override
public MqResult consume(String data) throws Exception {
logger.info("[Demo2MqComsumer] 消费一条消息:{}", data);
return MqResult.SUCCESS;
} }
import com.xxl.mq.client.consumer.IMqConsumer;
import com.xxl.mq.client.consumer.MqResult;
import com.xxl.mq.client.consumer.annotation.MqConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; /**
* Created by xuxueli on 16/8/28.
*/
@MqConsumer(topic = "topic_1")
@Service
public class DemoAMqComsumer implements IMqConsumer {
private Logger logger = LoggerFactory.getLogger(DemoAMqComsumer.class); @Override
public MqResult consume(String data) throws Exception {
logger.info("[DemoAMqComsumer] 消费一条消息:{}", data);
return MqResult.SUCCESS;
} }
import com.xxl.mq.client.consumer.IMqConsumer;
import com.xxl.mq.client.consumer.MqResult;
import com.xxl.mq.client.consumer.annotation.MqConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; /**
* Created by xuxueli on 16/8/28.
*/
@MqConsumer(topic = "topic_1")
@Service
public class DemoBMqComsumer implements IMqConsumer {
private Logger logger = LoggerFactory.getLogger(DemoBMqComsumer.class); @Override
public MqResult consume(String data) throws Exception {
logger.info("[DemoBMqComsumer] 消费一条消息:{}", data);
return MqResult.SUCCESS;
} }
import com.xxl.mq.client.consumer.IMqConsumer;
import com.xxl.mq.client.consumer.MqResult;
import com.xxl.mq.client.consumer.annotation.MqConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; /**
* Created by xuxueli on 16/8/28.
*/
@MqConsumer(topic = "topic_1", group = MqConsumer.EMPTY_GROUP)
@Service
public class DemoCMqComsumer implements IMqConsumer {
private Logger logger = LoggerFactory.getLogger(DemoCMqComsumer.class); @Override
public MqResult consume(String data) throws Exception {
logger.info("[DemoCMqComsumer] 消费一条消息:{}", data);
return MqResult.SUCCESS;
} }
springboot整合xxl-mq学习笔记的更多相关文章
- 这篇SpringBoot整合JSON的学习笔记,建议收藏起来,写的太细了
前言 JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛. 采用完全独立于编程语言的文本格式来存储和表示数据. 简洁和清晰 ...
- 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)
[原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...
- 搭建SpringBoot、Jsp支持学习笔记
Spring Boot 添加JSP支持 大体步骤: (1) 创建Maven web project: (2) 在pom.xml文件添加依赖: (3) ...
- springboot 尚桂谷学习笔记03
------spring boot 与日志------ 日志框架: 市面上的日志框架: jul jcl jboss-logging logback log4j log4j2 ...... 左边一个门面 ...
- 【mq学习笔记】mq查找路由信息与故障延迟
路由发现:缓存中的路由信息什么时候更新呢? 由QueueData转topicPublishInfo的List<QueueMessage>: 选择消息队列: sendLatencyFault ...
- 【mq学习笔记-分布式篇】主从同步机制
核心类: 消息消费到达主服务器后需要将消息同步到从服务器,如果主服务器Broker宕机后,消息消费者可以从从服务器拉取消息. HAService:RocketMQ主从同步核心实现类 HAService ...
- 【mq学习笔记】mq 过期文件删除机制
broker不会关注这个文件上的消息是否全部被消费.默认每个文件的过期时间为72小时.
- SpringBoot整合RabbitMQ-5.7-课堂笔记-02
- Git学习笔记与IntelliJ IDEA整合
Git学习笔记与IntelliJ IDEA整合 一.Git学习笔记(基于Github) 1.安装和配置Git 下载地址:http://git-scm.com/downloads Git简要使用说明:h ...
- [转]Git学习笔记与IntelliJ IDEA整合
Git学习笔记与IntelliJ IDEA整合 一.Git学习笔记(基于Github) 1.安装和配置Git 下载地址:http://git-scm.com/downloads Git简要使用说明:h ...
随机推荐
- jhipster初接触
在Windows7部署之前把几个依赖下了 jdk:1.80 Maven :3.3.9 git:2.14.1 npm:唯一要注意的就是配置一个阿里的镜像,不然慢的你崩溃 Yeoman: npm inst ...
- 解决Xcode在debug时不在断点处停止的方法<转>
搞了老半天不知道为什么 后来查了一下才解决问题,多谢原创作者的贡献. 新年后的第一发! -------------------------------- 前几天在开发的时候,Xcode设置断点后依然无 ...
- TCP/IP 笔记 1.1 概 述
四个层次 每一层负责不同的功能:1) 链路层,有时也称作数据链路层或网络接口层,通常包括操作系统中的设备驱动程序和计算机中对应的网络接口卡.它们一起处理与电缆(或其他任何传输媒介)的物理接口细节.2) ...
- Springboot中AOP统一处理请求日志
完善上面的代码: 现在把输出信息由先前的system.out.println()方式改为由日志输出(日志输出的信息更全面) 现在在日志中输出http请求的内容 在日志中获取方法返回的内容
- Win 2008 R2安装SQL Server 2008“性能计数器注册表配置单元一致性”失败的解决办法
Win 2008 R2安装SQL Server 2008“性能计数器注册表配置单元一致性”失败的解决办法(2011-02-23 19:37:32) 转载▼ 今天在惠普服务器上安装数据库2008时, ...
- php二维数组排序方法(array_multisort,usort)
一维数组排序可以使用asort.ksort等一些方法进程排序,相对来说比较简单.二维数组的排序怎么实现呢?使用array_multisort和usort可以实现 例如像下面的数组: $users = ...
- USB无线网卡导致耳机电流声很大
今天把许久未用的USB无线网卡插入到电脑中,戴上耳机准备听音乐,发现耳机里面的电流声非常大.回想以前并没有这种状况呀,忽然发现原来是USB无线网卡和耳机都插在前置面板中了,把USB无线网卡插在后置面板 ...
- C语言-郝斌笔记-001求二次方程的根
求二次方程的根 #include <stdio.h > #include<math.h> int main(void) { //把三个系数保存到计算机中 ; //=不表示相等, ...
- Mat 类的内存管理
使用 Mat 类,内存管理变得简单,不再像使用 IplImage 那样需要自己申请和释放内存.虽然不了解 Mat 的内存管理机制,也无碍于 Mat 类的使用,但是如果清楚了解 Mat 的内存管理,会更 ...
- Socket编程--基础(基本server/client实现)
IPv4套接口地址结构 IPv4套接口地址结构通常也称为“网际套接字地址结构”,它以“sockaddr_in”命名,定义在头文件中 LINUX结构下的常用结构,一般创建套接字的时候都要将这个结构里面的 ...