Commit 1eda9fa8 by 共享中心代码生成

Merge branch 'new-strut' into 'master'

New strut

See merge request !1
parents 78b5a8f2 e8f4fb9d
!.mvn/wrapper/maven-wrapper.jar
*.class
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
*.lst
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/mvnw
/mvnw.cmd
# "temporary" build files
target/
out/
build/
logs
# 简介
Matrix-sample是matrix组件的示例项目,包括redis、rocketmq等中间件以及提供通用util工具类使用方式等
\ No newline at end of file
<?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>
<artifactId>matrix-sample-dubbo</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-sample-dubbo-api</artifactId>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>common-core</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.secoo.mall.dubbo.bean;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
public class User implements Serializable {
@ApiModelProperty(value = "用户姓名")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
\ No newline at end of file
package com.secoo.mall.dubbo.service;
import com.secoo.mall.common.core.bean.BizResponse;
import com.secoo.mall.dubbo.bean.User;
public interface UserDService {
BizResponse<String> sayHello(String name);
User getByid(Long id);
}
\ No newline at end of file
......@@ -2,9 +2,14 @@
<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>
<artifactId>matrix-sample-dubbo</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.matrix</groupId>
<artifactId>dubbo-api</artifactId>
<version>1.0-SNAPSHOT</version>
<artifactId>matrix-sample-dubbo-spring</artifactId>
</project>
\ No newline at end of file
<?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>
<artifactId>matrix-sample-dubbo</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-sample-dubbo-springboot</artifactId>
</project>
\ No newline at end of file
<?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>
<artifactId>matrix-sample</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-sample-dubbo</artifactId>
<packaging>pom</packaging>
<modules>
<module>matrix-sample-dubbo-api</module>
<module>matrix-sample-dubbo-spring</module>
<module>matrix-sample-dubbo-springboot</module>
</modules>
</project>
\ No newline at end of file
<?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>
<artifactId>matrix-sample-xxl</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-sample-xxl-biz</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-xxl-core</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.secoo.mall.xxl.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* 命令行任务
*
* @author xuxueli 2018-09-16 03:48:34
*/
@JobHandler(value="commandJobHandler")
@Component
public class CommandJobHandler extends IJobHandler {
@Override
public ReturnT<String> execute(String param) throws Exception {
String command = param;
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobLogger.log(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobLogger.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
return IJobHandler.SUCCESS;
} else {
return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value("+exitValue+") is failed");
}
}
}
package com.secoo.mall.xxl.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* 任务Handler示例(Bean模式)
*
* 开发步骤:
* 1、继承"IJobHandler":“com.xxl.job.core.handler.IJobHandler”;
* 2、注册到Spring容器:添加“@Component”注解,被Spring容器扫描为Bean实例;
* 3、注册到执行器工厂:添加“@JobHandler(value="自定义jobhandler名称")”注解,注解value值对应的是调度中心新建任务的JobHandler属性的值。
* 4、执行日志:需要通过 "XxlJobLogger.log" 打印执行日志;
*
* @author xuxueli 2015-12-19 19:43:36
*/
@JobHandler(value="demoJobHandler")
@Component
public class DemoJobHandler extends IJobHandler {
@Override
public ReturnT<String> execute(String param) throws Exception {
XxlJobLogger.log("XXL-JOB, Hello World.");
System.out.println("DemoJobHandler");
for (int i = 0; i < 5; i++) {
XxlJobLogger.log("beat at:" + i);
TimeUnit.SECONDS.sleep(2);
}
return SUCCESS;
}
}
package com.secoo.mall.xxl.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 跨平台Http任务
*
* @author xuxueli 2018-09-16 03:48:34
*/
@JobHandler(value = "httpJobHandler")
@Component
public class HttpJobHandler extends IJobHandler {
@Override
public ReturnT<String> execute(String param) throws Exception {
// request
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(param);
connection = (HttpURLConnection) realUrl.openConnection();
// connection setting
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(3 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
// do connection
connection.connect();
//Map<String, List<String>> map = connection.getHeaderFields();
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
// result
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
String responseMsg = result.toString();
XxlJobLogger.log(responseMsg);
return SUCCESS;
} catch (Exception e) {
XxlJobLogger.log(e);
return FAIL;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobLogger.log(e2);
}
}
}
}
package com.secoo.mall.xxl.jobhandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import org.springframework.stereotype.Component;
/**
* 分片广播任务
*
* @author xuxueli 2017-07-25 20:56:50
*/
@JobHandler(value="shardingJobHandler")
@Component
public class ShardingJobHandler extends IJobHandler {
@Override
public ReturnT<String> execute(String param) throws Exception {
// 分片参数
ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
XxlJobLogger.log("分片参数:当前分片序号 = {}, 总分片数 = {}", shardingVO.getIndex(), shardingVO.getTotal());
// 业务逻辑
for (int i = 0; i < shardingVO.getTotal(); i++) {
if (i == shardingVO.getIndex()) {
XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
} else {
XxlJobLogger.log("第 {} 片, 忽略", i);
}
}
return SUCCESS;
}
}
package com.secoo.mall.xxl.xxljob;
import com.secoo.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
* XxlJob开发示例(Bean模式)
* <p>
* 开发步骤:
* 1、在Spring Bean实例中,开发Job方法,方式格式要求为 "public ReturnT<String> execute(String param)"
* 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")",注解value值对应的是调度中心新建任务的JobHandler属性的值。
* 注意事项:
* 1、方法名称必须全局唯一,并且与IJobHandler类名不能有重复
*
* @author xuxueli 2019-12-11 21:52:51
*/
@Component
@Slf4j
public class SampleXxlJob {
/**
* 1、简单任务示例(Bean模式)
*/
@XxlJob("demoJobHandler2")
public ReturnT<String> demoJobHandler2(String param) throws Exception {
log.info("###demoJobHandler2");
XxlJobLogger.log("Annotation demoJobHandler XXL-JOB, Hello World.");
for (int i = 0; i < 5; i++) {
XxlJobLogger.log("beat at:" + i);
TimeUnit.SECONDS.sleep(2);
}
return ReturnT.SUCCESS;
}
/**
* 2、分片广播任务
*/
@XxlJob("shardingJobHandler2")
public ReturnT<String> shardingJobHandler(String param) throws Exception {
// 分片参数
ShardingUtil.ShardingVO shardingVO = ShardingUtil.getShardingVo();
XxlJobLogger.log("Annotation 分片参数:当前分片序号 = {}, 总分片数 = {}", shardingVO.getIndex(), shardingVO.getTotal());
// 业务逻辑
for (int i = 0; i < shardingVO.getTotal(); i++) {
if (i == shardingVO.getIndex()) {
XxlJobLogger.log("第 {} 片, 命中分片开始处理", i);
} else {
XxlJobLogger.log("第 {} 片, 忽略", i);
}
}
return ReturnT.SUCCESS;
}
/**
* 3、命令行任务
*/
@XxlJob("commandJobHandler2")
public ReturnT<String> commandJobHandler(String param) throws Exception {
String command = param;
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
Process process = Runtime.getRuntime().exec(command);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
XxlJobLogger.log(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
XxlJobLogger.log(e);
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
return IJobHandler.SUCCESS;
} else {
return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value(" + exitValue + ") is failed");
}
}
/**
* 4、跨平台Http任务
*/
@XxlJob("httpJobHandler2")
public ReturnT<String> httpJobHandler(String param) throws Exception {
// request
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(param);
connection = (HttpURLConnection) realUrl.openConnection();
// connection setting
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5 * 1000);
connection.setConnectTimeout(3 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
// do connection
connection.connect();
//Map<String, List<String>> map = connection.getHeaderFields();
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
}
// result
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
String responseMsg = result.toString();
XxlJobLogger.log(responseMsg);
return ReturnT.SUCCESS;
} catch (Exception e) {
XxlJobLogger.log(e);
return ReturnT.FAIL;
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
XxlJobLogger.log(e2);
}
}
}
/**
* 5、生命周期任务示例:任务初始化与销毁时,支持自定义相关逻辑;
*/
@XxlJob(value = "springBeanJobHandler2", init = "init", destroy = "destroy")
public ReturnT<String> springBeanJobHandler2(String param) throws Exception {
XxlJobLogger.log("XXL-JOB, Hello World.");
return ReturnT.SUCCESS;
}
public void init() {
log.info("init");
}
public void destroy() {
log.info("destory");
}
}
......@@ -2,51 +2,23 @@
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>matrix</artifactId>
<artifactId>matrix-sample-xxl</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.2.12.RELEASE</version>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<java.version>1.8</java.version>
<dubbo.version>2.7.0</dubbo.version>
</properties>
<artifactId>consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.matrix</groupId>
<artifactId>dubbo-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-starter</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
<artifactId>matrix-sample-xxl-spring</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-sample-xxl-biz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
<?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:context="http://www.springframework.org/schema/context" xmlns:apollo="http://www.ctrip.com/schema/apollo"
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.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<context:property-placeholder location="classpath*:*.properties"/>
<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<apollo:config/>
<!-- ********************************* 基础配置 ********************************* -->
<!-- 配置01、JobHandler 扫描路径 -->
<context:component-scan base-package="com.secoo.mall.xxl" />
<!-- 配置02、执行器 -->
<bean id="xxlJobSpringExecutor" class="com.secoo.xxl.job.core.executor.impl.XxlJobSpringExecutor" init-method="start" destroy-method="destroy" >
<!-- 执行器注册中心地址[选填],为空则关闭自动注册 -->
<property name="adminAddresses" value="${xxl.job.admin-addresses}" />
<!-- 执行器AppName[选填],为空则关闭自动注册.如果接入配置中心,默认会读取app.properties中的app.id-->
<property name="appName" value="${xxl.job.appname}" />
<!-- 执行器IP[选填],为空则自动获取 -->
<property name="ip" value="${xxl.job.executor.ip}" />
<!-- 执行器端口号[选填],小于等于0则自动获取 -->
<property name="port" value="${xxl.job.executor.port}" />
<!-- 访问令牌[选填],非空则进行匹配校验 -->
<property name="accessToken" value="${xxl.job.accessToken}" />
<!-- 执行器日志路径[选填],为空则使用默认路径 -->
<property name="logPath" value="${xxl.job.logpath}" />
<!-- 日志保存天数[选填],值大于3时生效 -->
<property name="logRetentionDays" value="${xxl.job.logretentiondays}" />
</bean>
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//log4j/log4j Configuration//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" threshold="null" debug="null">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-spring [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="/data/applogs/xxl-job/xxl-job-executor-sample-spring.log"/>
<param name="append" value="true"/>
<param name="encoding" value="UTF-8"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss} xxl-job-executor-sample-spring [%c]-[%t]-[%M]-[%L]-[%p] %m%n"/>
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
<!--<logger name="com.xxl.job.executor.service.jobhandler" additivity="false">
<level value="INFO" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</logger>-->
</log4j:configuration>
\ No newline at end of file
<?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-job/xxl-job-executor-sample-springboot.log"/>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %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{36} [%file : %line] %msg%n
</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="console"/>
<appender-ref ref="file"/>
</root>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>xxl-job-executor-sample-spring</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>xxl-job-executor-sample-spring</param-value>
</context-param>
<!-- spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationcontext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
\ No newline at end of file
#### xxl-job admin address list, such as "http://address" or "http://address01,http://address02"
#xxl.job.admin-addresses=http://127.0.0.1:8080/xxl-job-admin
#
#### xxl-job executor address
#xxl.job.appname=xxl-job-app
#xxl.job.executor.ip=
#xxl.job.executor.port=9998
#
#### xxl-job, access token
#xxl.job.accessToken=
#
#### xxl-job log path
#xxl.job.logpath=/data/applogs/xxl-job/jobhandler
#### xxl-job log retention days
#xxl.job.logretentiondays=-1
......@@ -2,47 +2,27 @@
<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">
<modelVersion>4.0.0</modelVersion>
<artifactId>provider</artifactId>
<parent>
<artifactId>matrix</artifactId>
<artifactId>matrix-sample-xxl</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.2.12.RELEASE</version>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.matrix</groupId>
<artifactId>dubbo-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-protocol-dubbo-starter</artifactId>
</dependency>
</dependencies>
<artifactId>matrix-sample-xxl-springboot</artifactId>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-sample-xxl-biz</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-job-xxl-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.matrix.grpc;
package com.secoo.mall.xxl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author qianglu
* @author xuxueli 2018-10-28 00:38:13
*/
@SpringBootApplication
public class PureStartup {
public class XxlJobExecutorApplication {
public static void main(String[] args) {
SpringApplication.run(PureStartup.class, args);
SpringApplication.run(XxlJobExecutorApplication.class, args);
}
}
}
\ No newline at end of file
server:
port: 8081
spring:
application:
name: xxl-job-app
xxl:
job:
admin-addresses: http://job.secoolocal.com #xxl-admin访问地址,必填。如开发环境 http://job.secoolocal.com
#executor:
# ip: 127.0.0.1 # 定时任务执行主机IP,非必填。默认为空
# port: #定时任务执行主机端口,非必填。默认9999.
#access-token: #默认为空
#log-path: #xxl日志存储地址,非必填。目录默认位置:c:/opt(windows)或者/data/logs(linux)
#log-retention-days: #日志保存时间,非必填。默认7天
#app-name: # 执行器名称,非必填。默认会读取spring.application.name
# enabled: 是否启用xxl,默认为true。
<?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>
<artifactId>matrix-sample</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.3.2.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>matrix-sample-xxl</artifactId>
<packaging>pom</packaging>
<modules>
<module>matrix-sample-xxl-spring</module>
<module>matrix-sample-xxl-springboot</module>
<module>matrix-sample-xxl-biz</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-sample-xxl-biz</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
\ No newline at end of file
<?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">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<modules>
<module>matrix-sample-xxl</module>
<module>matrix-sample-dubbo</module>
</modules>
<parent>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<artifactId>matrix-sample</artifactId>
</project>
\ No newline at end of file
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.matrix</groupId>
<artifactId>spring-boot-agent-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
package com.matrix.agent.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* @author qianglu
*/
@SpringBootApplication
public class AgentDemoStartup extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AgentDemoStartup.class);
}
public static void main(String[] args) {
//
SpringApplication.run(AgentDemoStartup.class, args);
}
}
package com.matrix.agent.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 异步线程配置
*
* @author QIANGLU on 2019/9/26
*/
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfig {
@Value("${sms.executor.corePoolSize:5}")
private int corePoolSize;
@Value("${sms.executor.maxPoolSize:10}")
private int maxPoolSize;
@Value("${sms.executor.queueCapacity:200}")
private int queueCapacity;
@Bean(name = "mailAsync")
public Executor mailAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("MailExecutor-");
executor.initialize();
return executor;
}
}
\ No newline at end of file
package com.matrix.agent.demo.test;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author QIANGLU on 2019-09-02
*/
@Component
public class Test {
@Scheduled(fixedDelay = 1000)
private void fun1() throws Exception {
System.out.println("this is fun 1.");
}
private void fun2() throws Exception {
System.out.println("this is fun 2.");
Thread.sleep(500);
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test.fun1();
test.fun2();
}
}
\ No newline at end of file
spring:
application:
name: agent-demo
server:
port: 6080
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-agent</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.11.0.GA</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.10.1</version>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.10.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Premain-Class>com.qianglu.agent.AgentStartup</Premain-Class>
<Agent-Class>com.qianglu.agent.AgentStartup</Agent-Class>
<Can-Redefine-Classes>true</Can-Redefine-Classes>
<Can-Retransform-Classes>true</Can-Retransform-Classes>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<artifactSet>
<includes>
<include>javassist:javassist:jar:</include>
<include>net.bytebuddy:byte-buddy:jar:</include>
<include>net.bytebuddy:byte-buddy-agent:jar:</include>
</includes>
</artifactSet>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
package com.qianglu.agent;
import com.qianglu.agent.config.TimeInterceptor;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;
import java.lang.instrument.Instrumentation;
/**
* @author qianglu
*/
public class AgentStartup {
public static void premain(String arg, Instrumentation instrumentation) {
System.err.println("agent startup , args is " + arg);
// instrumentation.addTransformer(new PerformMonitorTransformer());
AgentBuilder.Transformer transformer = new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule) {
return builder
.method(ElementMatchers.any()) // 拦截任意方法
.intercept(MethodDelegation.to(TimeInterceptor.class));
}
};
AgentBuilder.Listener listener = new AgentBuilder.Listener() {
@Override
public void onDiscovery(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {
}
@Override
public void onTransformation(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b, DynamicType dynamicType) {
}
@Override
public void onIgnored(TypeDescription typeDescription, ClassLoader classLoader, JavaModule javaModule, boolean b) {
}
@Override
public void onError(String s, ClassLoader classLoader, JavaModule javaModule, boolean b, Throwable throwable) {
}
@Override
public void onComplete(String s, ClassLoader classLoader, JavaModule javaModule, boolean b) {
}
};
new AgentBuilder.Default().type(ElementMatchers.any()).transform(transformer).with(listener).installOn(instrumentation);
}
}
package com.qianglu.agent.config;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
/**
* @author QIANGLU on 2019-09-02
*/
public class TimeInterceptor {
@RuntimeType
public static Object intercept(@Origin Method method,
@SuperCall Callable<?> callable) throws Exception {
long start = System.currentTimeMillis();
try {
// 原有函数执行
return callable.call();
} finally {
System.out.println(method + ": took " + (System.currentTimeMillis() - start) + "ms");
}
}
}
\ No newline at end of file
package com.qianglu.agent.service;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.List;
/**
* 测试下载
*
* @author QIANGLU on 2019-08-15
*/
public class DumpClassesService implements ClassFileTransformer {
private static final List<String> SYSTEM_CLASS_PREFIX = Arrays.asList("java", "sum", "jdk");
public static void main(String[] args) throws ClassNotFoundException {
boolean loaderIsAvailable = null != Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
System.out.println(loaderIsAvailable);
}
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (!isSystemClass(className)) {
System.out.println("load class " + className);
FileOutputStream fos = null;
try {
// 将类名统一命名为classNamedump.class格式
fos = new FileOutputStream(className + "dump.class");
fos.write(classfileBuffer);
fos.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
// 关闭文件输出流
if (null != fos) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return classfileBuffer;
}
/**
* 判断一个类是否为系统类
*
* @param className 类名
* @return System Class then return true,else return false
*/
private boolean isSystemClass(String className) {
// 假设系统类的类名不为NULL而且不为空
if (null == className || className.isEmpty()) {
return false;
}
for (String prefix : SYSTEM_CLASS_PREFIX) {
if (className.startsWith(prefix)) {
return true;
}
}
return false;
}
}
\ No newline at end of file
package com.qianglu.agent.service;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.HashSet;
import java.util.Set;
/**
* 测试
*
* @author QIANGLU on 2019-09-02
*/
public class PerformMonitorTransformer implements ClassFileTransformer {
private static final Set<String> classNameSet = new HashSet<>();
static {
classNameSet.add("com.example.demo.AgentTest");
}
@Override
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer) throws IllegalClassFormatException {
try {
String currentClassName = className.replaceAll("/", ".");
if (!classNameSet.contains(currentClassName)) { // 仅仅提升Set中含有的类
return null;
}
System.out.println("transform: [" + currentClassName + "]");
CtClass ctClass = ClassPool.getDefault().get(currentClassName);
CtBehavior[] methods = ctClass.getDeclaredBehaviors();
for (CtBehavior method : methods) {
enhanceMethod(method);
}
return ctClass.toBytecode();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void enhanceMethod(CtBehavior method) throws Exception {
if (method.isEmpty()) {
return;
}
String methodName = method.getName();
if (methodName.equalsIgnoreCase("main")) { // 不提升main方法
return;
}
final StringBuilder source = new StringBuilder();
source.append("{")
.append("long start = System.nanoTime();\n") // 前置增强: 打入时间戳
.append("$_ = $proceed($$);\n") // 保留原有的代码处理逻辑
.append("System.out.print(\"method:[" + methodName + "]\");").append("\n")
.append("System.out.println(\" cost:[\" +(System.nanoTime() -start)+ \"ns]\");") // 后置增强
.append("}");
ExprEditor editor = new ExprEditor() {
@Override
public void edit(MethodCall methodCall) throws CannotCompileException {
methodCall.replace(source.toString());
}
};
method.instrument(editor);
}
}
\ No newline at end of file
spring:
application:
name: learn-agent
server:
port: 6080
package com.matrix.dubbo.consumer;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author qianglu
*/
@SpringBootApplication
@EnableDubboConfig
public class ConsumerStartup {
public static void main(String[] args) {
SpringApplication.run(ConsumerStartup.class, args);
}
}
package com.matrix.dubbo.consumer.controller;
import com.alibaba.dubbo.common.Constants;
import com.matrix.dubbo.api.DemoService;
import com.matrix.dubbo.consumer.service.ConsumerService;
import com.matrix.dubbo.consumer.service.ConsumerServiceImpl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.store.DataStore;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.rpc.Filter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
/**
* @ClassName DemoController
* @Author QIANGLU
* @Date 2020/2/4 3:37 下午
* @Version 1.0
*/
@RestController
@RequestMapping("/consumer")
public class ConusmerController {
@Resource
private ConsumerService consumerService;
@RequestMapping("/demo")
public String getDemo() {
return consumerService.getConsumer();
}
@RequestMapping("/clazz")
public String clazz() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
boolean loaderIsAvailable = null != Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
if (loaderIsAvailable) {
Class<?> loaderClazz = Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
Class<?> dataStore = Class.forName("org.apache.dubbo.common.store.DataStore");
Method method = loaderClazz.getDeclaredMethod("getExtensionLoader", Class.class);
Object loader = method.invoke(null, dataStore);
Method def = loaderClazz.getDeclaredMethod("getDefaultExtension");
Object extension = def.invoke(loader);
Class<?> storeClazz = extension.getClass();
Method getstore = storeClazz.getDeclaredMethod("get",String.class);
Map<String, Object> executors = (Map<String, Object>) getstore.invoke(extension, ExecutorService.class.getName());
System.out.println(executors);
// ExtensionLoader extensionLoader = ExtensionLoader.getExtensionLoader(DataStore.class);
// ExtensionLoader extensionLThreadPooloader = ExtensionLoader.getExtensionLoader(ThreadPool.class);
// ExtensionLoader s = ExtensionLoader.getExtensionLoader(ThreadPool.class);
}
return consumerService.getConsumer();
}
}
package com.matrix.dubbo.consumer.service;
/**
* @ClassName ConsumerService
* @Author QIANGLU
* @Date 2020/2/4 4:18 下午
* @Version 1.0
*/
public interface ConsumerService {
public String getConsumer();
}
package com.matrix.dubbo.consumer.service;
import com.matrix.dubbo.api.DemoService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @ClassName ConsumerService
* @Author QIANGLU
* @Date 2020/2/4 4:03 下午
* @Version 1.0
*/
@Service
public class ConsumerServiceImpl implements ConsumerService {
@Reference(version = "${demo.service.version}" ,check = false)
private DemoService demoService;
@Override
public String getConsumer() {
return demoService.getDemo();
}
}
package com.matrix.dubbo.consumer.service;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
/**
* @ClassName TestFilter
* @Author QIANGLU
* @Date 2020/3/5 5:11 下午
* @Version 1.0
*/
@Activate(group ={"consumer","provider"},order = 4 )
public class TestFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return null;
}
public static void main(String[] args) throws ClassNotFoundException {
boolean loaderIsAvailable = null != Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
System.out.println(loaderIsAvailable);
}
}
test=com.matrix.dubbo.consumer.service.TestFilter
\ No newline at end of file
spring:
application:
name: consumer
main:
allow-bean-definition-overriding: true
server:
port: 6081
dubbo:
protocol:
name: dubbo
port: 11135
status: threadpool,memory,load
registry:
address: zookeeper://127.0.0.1:2181
scan:
base-packages: com.matrix.dubbo
application:
qos-enable: true
provider:
status: threadpool,memory,load
demo:
service:
version: 1.0
management:
endpoints:
web:
exposure:
include: dubbo,dubbo-configs,dubbo-properties,health
package com.matrix.dubbo.api;
/**
* @ClassName DemoService
* @Author QIANGLU
* @Date 2020/2/4 3:30 下午
* @Version 1.0
*/
public interface DemoService {
String getDemo();
}
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-dubbo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>consumer</module>
<module>provider</module>
<module>dubbo-api</module>
</modules>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
<dubbo.version>2.7.0</dubbo.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.matrix.dubbo.provider;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.util.ErrorHandler;
import org.springframework.util.SocketUtils;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.UUID;
/**
* from: https://github.com/spring-projects/spring-xd/blob/v1.3.1.RELEASE/spring-xd-dirt/src/main/java/org/springframework/xd/dirt/zookeeper/ZooKeeperUtils.java
* <p>
* Helper class to start an embedded instance of standalone (non clustered) ZooKeeper.
* <p>
* NOTE: at least an external standalone server (if not an ensemble) are recommended, even for
* org.springframework.xd.dirt.server.singlenode.SingleNodeApplication
*
* @author Patrick Peralta
* @author Mark Fisher
* @author David Turanski
*/
public class EmbeddedZooKeeper implements SmartLifecycle {
/**
* Logger.
*/
private static final Logger logger = LoggerFactory.getLogger(EmbeddedZooKeeper.class);
/**
* ZooKeeper client port. This will be determined dynamically upon startup.
*/
private final int clientPort;
/**
* Whether to auto-start. Default is true.
*/
private boolean autoStartup = true;
/**
* Lifecycle phase. Default is 0.
*/
private int phase = 0;
/**
* Thread for running the ZooKeeper server.
*/
private volatile Thread zkServerThread;
/**
* ZooKeeper server.
*/
private volatile ZooKeeperServerMain zkServer;
/**
* {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread.
*/
private ErrorHandler errorHandler;
private boolean daemon = true;
/**
* Construct an EmbeddedZooKeeper with a random port.
*/
public EmbeddedZooKeeper() {
clientPort = SocketUtils.findAvailableTcpPort();
}
/**
* Construct an EmbeddedZooKeeper with the provided port.
*
* @param clientPort port for ZooKeeper server to bind to
* @param daemon is daemon or not thread.
*/
public EmbeddedZooKeeper(int clientPort, boolean daemon) {
this.clientPort = clientPort;
this.daemon = daemon;
}
/**
* Returns the port that clients should use to connect to this embedded server.
*
* @return dynamically determined client port
*/
public int getClientPort() {
return this.clientPort;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
/**
* Specify whether to start automatically. Default is true.
*
* @param autoStartup whether to start automatically
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
/**
* {@inheritDoc}
*/
@Override
public int getPhase() {
return this.phase;
}
/**
* Specify the lifecycle phase for the embedded server.
*
* @param phase the lifecycle phase
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isRunning() {
return (zkServerThread != null);
}
/**
* Start the ZooKeeper server in a background thread.
* <p>
* Register an error handler via {@link #setErrorHandler} in order to handle
* any exceptions thrown during startup or execution.
*/
@Override
public synchronized void start() {
if (zkServerThread == null) {
zkServerThread = new Thread(new ServerRunnable(), "ZooKeeper Server Starter");
zkServerThread.setDaemon(daemon);
zkServerThread.start();
}
}
/**
* Shutdown the ZooKeeper server.
*/
@Override
public synchronized void stop() {
if (zkServerThread != null) {
// The shutdown method is protected...thus this hack to invoke it.
// This will log an exception on shutdown; see
// https://issues.apache.org/jira/browse/ZOOKEEPER-1873 for details.
try {
Method shutdown = ZooKeeperServerMain.class.getDeclaredMethod("shutdown");
shutdown.setAccessible(true);
shutdown.invoke(zkServer);
} catch (Exception e) {
throw new RuntimeException(e);
}
// It is expected that the thread will exit after
// the server is shutdown; this will block until
// the shutdown is complete.
try {
zkServerThread.join(5000);
zkServerThread = null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn("Interrupted while waiting for embedded ZooKeeper to exit");
// abandoning zk thread
zkServerThread = null;
}
}
}
/**
* Stop the server if running and invoke the callback when complete.
*/
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
/**
* Provide an {@link ErrorHandler} to be invoked if an Exception is thrown from the ZooKeeper server thread. If none
* is provided, only error-level logging will occur.
*
* @param errorHandler the {@link ErrorHandler} to be invoked
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Runnable implementation that starts the ZooKeeper server.
*/
private class ServerRunnable implements Runnable {
@Override
public void run() {
try {
Properties properties = new Properties();
File file = new File(System.getProperty("java.io.tmpdir")
+ File.separator + UUID.randomUUID());
file.deleteOnExit();
properties.setProperty("dataDir", file.getAbsolutePath());
properties.setProperty("clientPort", String.valueOf(clientPort));
QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig();
quorumPeerConfig.parseProperties(properties);
zkServer = new ZooKeeperServerMain();
ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumPeerConfig);
zkServer.runFromConfig(configuration);
} catch (Exception e) {
if (errorHandler != null) {
errorHandler.handleError(e);
} else {
logger.error("Exception running embedded ZooKeeper", e);
}
}
}
}
}
package com.matrix.dubbo.provider;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
/**
* @author qianglu
*/
@SpringBootApplication
@EnableDubboConfig
public class ProviderStartup {
public static void main(String[] args) {
new SpringApplicationBuilder(ProviderStartup.class)
.listeners((ApplicationListener<ApplicationEnvironmentPreparedEvent>) event -> {
Environment environment = event.getEnvironment();
new EmbeddedZooKeeper(2181, false).start();
})
.run(args);
}
}
package com.matrix.dubbo.provider.service;
import com.matrix.dubbo.api.DemoService;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.store.DataStore;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
/**
* @ClassName DemoServiceImpl
* @Author QIANGLU
* @Date 2020/2/4 3:29 下午
* @Version 1.0
*/
@Service(version = "1.0")
public class DemoProviderServiceImpl implements DemoService {
@Override
public String getDemo() {
DataStore s = ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();
try {
boolean loaderIsAvailable = null != Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
// if (loaderIsAvailable) {
// Class<?> loaderClazz = Class.forName("org.apache.dubbo.common.extension.ExtensionLoader");
// Class<?> dataStore = Class.forName("org.apache.dubbo.common.store.DataStore");
// Method method = loaderClazz.getDeclaredMethod("getExtensionLoader", Class.class);
// Object loader = method.invoke(null, dataStore);
//
// Method def = loaderClazz.getDeclaredMethod("getDefaultExtension");
// Object extension = def.invoke(loader);
//
// Class<?> storeClazz = extension.getClass();
// Method getstore = storeClazz.getDeclaredMethod("get", String.class);
// Map<String, Object> executors = (Map<String, Object>) getstore.invoke(extension, ExecutorService.class.getName());
// System.out.println(executors);
// }
} catch (Exception e) {
}
return "this is provider ";
}
}
spring:
application:
name: provider
server:
port: 6080
dubbo:
protocol:
name: dubbo
port: 11134
threadpool: fixed
threads: 100
registry:
address: zookeeper://127.0.0.1:2181
scan:
base-packages: com.matrix.dubbo.provider.service
application:
qos-enable: true
provider:
status: threadpool,memory,load
demo:
service:
version: 1.0
embedded:
zookeeper:
port: 2181
management:
endpoints:
dubbo:
enabled: true
status:
defaults: load,threadpool
web:
exposure:
include: matrixlog,health,info,load,threadpool
\ No newline at end of file
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-grpc</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.25.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.25.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.25.0</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.25.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.matrix.grpc;
import com.takumiCX.greeter.GreeterGrpc;
import com.takumiCX.greeter.HelloReply;
import com.takumiCX.greeter.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.logging.Logger;
/**
* @ClassName GreeterImpl
* @Author QIANGLU
* @Date 2019/11/20 11:12 上午
* @Version 1.0
*/
public class GreeterImpl extends GreeterGrpc.GreeterImplBase {
private static final Logger log=Logger.getLogger(GreeterImpl.class.getName());
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
//构建响应消息,从请求消息中获取姓名,在前面拼接上"Hello "
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + request.getName()).build();
//在流关闭或抛出异常前可以调用多次
responseObserver.onNext(reply);
//关闭流
responseObserver.onCompleted();
}
public static void main(String[] args) throws IOException, InterruptedException {
int port = 50051;
Server server = ServerBuilder.forPort(port).addService(new GreeterImpl()).build().start();
log.info("Server started,listening on "+port);
server.awaitTermination();
}
}
package com.matrix.grpc;
import com.takumiCX.greeter.GreeterGrpc;
import com.takumiCX.greeter.HelloGrpc;
import com.takumiCX.greeter.HelloReply;
import com.takumiCX.greeter.HelloRequest;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import java.util.Scanner;
import java.util.logging.Logger;
/**
* @ClassName HelloWordClient
* @Author QIANGLU
* @Date 2019/11/20 11:23 上午
* @Version 1.0
*/
public class HelloWordClient {
private static final Logger log= Logger.getLogger(HelloWordClient.class.getName());
public static void main(String[] args) {
int port = 50051;
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost",port).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
Scanner scanner = new Scanner(System.in);
while(true){
String name = scanner.nextLine().trim();
HelloRequest helloRequest = HelloRequest.newBuilder().setName(name).build();
HelloReply helloReply = stub.sayHello(helloRequest);
log.info("message"+ helloReply.getMessage());
}
}
}
//Protocal Buffers的版本有v2和v3之分,语法有较多变化,且相互不兼容
//这里使用的v3版本的
syntax = "proto3";
//编译后生成的消息类HelloRequest和HelloReply是否分别放在单独的class文件中
option java_multiple_files = true;
//生成代码的包路径
option java_package = "com.takumiCX.greeter";
//最外层的类名称
option java_outer_classname = "HelloWorldProto";
//包命名空间
package helloworld;
// 服务接口
service Greeter {
// 一个简单的rpc方法
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
service Hello{
rpc hello(HelloRequest) returns (HelloReply){}
}
// 请求消息
message HelloRequest {
string name = 1;
}
// 响应消息
message HelloReply {
string message = 1;
}
\ No newline at end of file
spring:
application:
name: learn-grpc
server:
port: 6080
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-pure</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
spring:
application:
name: learn-pure
server:
port: 6080
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-redis</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>redis-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
package com.matrix.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author qianglu
*/
@SpringBootApplication
public class RedisStartup {
public static void main(String[] args) {
SpringApplication.run(RedisStartup.class, args);
}
}
package com.matrix.redis;
import com.secoo.mall.redis.utils.MatrixRedisClusterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.SendResult;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName RedisDemoService
* @Author QIANGLU
* @Date 2019/12/11 3:45 下午
* @Version 1.0
*/
@Component
public class RedisDemoService implements Runnable {
private Logger logger = LoggerFactory.getLogger(RedisDemoService.class);
private ScheduledFuture<?> scheduledFuture;
private volatile AtomicInteger count = new AtomicInteger();
public RedisDemoService() {
scheduledFuture = Executors
.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this, 0, 1, TimeUnit.SECONDS);
}
@Override
public void run() {
try {
//存入Redis
MatrixRedisClusterUtils.opsForHash().put("test_hashs", "hash", count.incrementAndGet()+"_hash");
logger.info("存入Redis Hash 数据 key:{},val:{}", "test_hashs_t1", count.get());
//set
MatrixRedisClusterUtils.opsForSet().add("test_sets", count.get() + "_set");
logger.info("存入Redis Set 数据 key:{},val:{}", "test_sets", count.get());
MatrixRedisClusterUtils.opsForValue().set("test_string", count.get() + "_string");
logger.info("存入Redis Value 数据 key:{},val:{}", "test_string", count.get());
//更多方法请查看 MatrixRedisClusterUtils
//取出
Object obj = MatrixRedisClusterUtils.opsForHash().get("test_hashs", "hash");
logger.info("取出Redis Hash 数据 key:{},val:{}", "test_hashs", obj);
//set
Set<String> sets = MatrixRedisClusterUtils.opsForSet().members("test_set");
logger.info("取出Redis Set 数据 key:{},size:{}", "test_set", sets.size());
String val = MatrixRedisClusterUtils.opsForValue().get("test_string");
logger.info("取出Redis Set 数据 key:{},val:{}", "test_string", val);
System.out.println("===========================================");
} catch (Exception e) {
System.out.println(e);
}
}
}
server:
port: 6080
spring:
application:
name: learn-redis
redis: # 配置可放入Apollo
host: 10.0.253.9 #单机模式下使用此配置
# cluster: 集群模式下打开此注解
# nodes: 192.168.xx.4:7000,192.168.xx.14:7002,192.168.xx.18:7004
# max-redirects: 6
lettuce:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 8 # 连接池中的最小空闲连接
max-wait: 2000 # 连接池最大阻塞等待时间(使用负值表示没有限制)
timeout: 2000 # 连接超时时间(毫秒)
<?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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nova</groupId>
<artifactId>spring-boot-rocketmq</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.1.8.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>logger-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.secoo.mall</groupId>
<artifactId>rocketmq-starter</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
\ No newline at end of file
package com.matrix.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @ClassName RcoketStartup
* @Author QIANGLU
* @Date 2019/11/28 4:00 下午
* @Version 1.0
*/
@SpringBootApplication
public class RcoketStartup {
public static void main(String[] args) {
SpringApplication.run(RcoketStartup.class, args);
}
}
package com.matrix.redis.rocketmq;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName ConsumerListener
* @Author QIANGLU
* @Date 2019/11/28 3:53 下午
* @Version 1.0
*/
@Component
@RocketMQMessageListener(topic = "topic", consumerGroup = "exwarngroup")
public class ConsumerListener implements RocketMQListener<String> {
private final static Logger log = LoggerFactory.getLogger(ConsumerListener.class);
private volatile AtomicInteger count = new AtomicInteger();
@Override
public void onMessage(String message) {
log.info(" consumer count:{}",count.incrementAndGet());
}
}
package com.matrix.redis.rocketmq;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName SendRocketService
* @Author QIANGLU
* @Date 2019/11/28 3:47 下午
* @Version 1.0
*/
@Component
public class SendRocketDemo implements Runnable {
private Logger logger = LoggerFactory.getLogger(SendRocketDemo.class);
@Resource
private RocketMQTemplate rocketMQTemplate;
private ScheduledFuture<?> scheduledFuture;
private volatile AtomicInteger count = new AtomicInteger();
public SendRocketDemo(){
scheduledFuture = Executors
.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this,0,1,TimeUnit.SECONDS);
}
@Override
public void run() {
//发送 Demo
try {
Message message = new Message();
//设置 body
message.setBody("我是一条测试信息".getBytes());
//设置tag
message.setTags("demo");
//同步发送 第一个参数是topic
SendResult sendResult = rocketMQTemplate.syncSend("topic",message);
//异步发送
rocketMQTemplate.asyncSend("topic",message,null,0);
}catch (Exception e){
logger.error("发送MQ异常",e);
}
}
}
spring:
application:
name: learn-rocketmq
server:
port: 6080
rocketmq:
name-server: 10.0.254.191:9876;10.0.254.206:9876
producer:
group: learn-rocketmq
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment