Commit 7777f138 by qiuweili123

重建结构

parent 78b5a8f2
......@@ -3,8 +3,10 @@
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>dubbo-api</artifactId>
<groupId>com.secoo.mall</groupId>
<artifactId>matrix-sample</artifactId>
<version>1.0-SNAPSHOT</version>
</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
<?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>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.2.12.RELEASE</version>
</parent>
<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
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
<?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>
<artifactId>provider</artifactId>
<parent>
<artifactId>matrix</artifactId>
<groupId>com.secoo.mall</groupId>
<version>1.2.12.RELEASE</version>
</parent>
<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>
</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
package com.matrix.grpc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author qianglu
*/
@SpringBootApplication
public class PureStartup {
public static void main(String[] args) {
SpringApplication.run(PureStartup.class, args);
}
}
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