diff --git a/README b/README new file mode 100644 index 0000000..a9fefc9 --- /dev/null +++ b/README @@ -0,0 +1,26 @@ +# SpringBootDemo +本代码集成了SpringBoot+MyBatis+Redis+MySql。 +最新的部分经网友指正已经把冗余的代码去掉了,大家clone到本地后直接转成maven项目应该就可以运行了,项目中使用到的数据库表如下 + +1.修改了application.yml中未使用原生配置项的问题 + +2.redis的配置可以使用redisTemplate,也可以使用RedisConfig和RediscoverUtil,两者并没有太大区别,只是RedisTemplate用接口。 + +3.MyBatis的配置放到了Resource下面。 + +-- ---------------------------- +-- Table structure for `user_info` +-- ---------------------------- +DROP TABLE IF EXISTS `user_info`; +CREATE TABLE `user_info` ( + `id` int(8) NOT NULL AUTO_INCREMENT, + `name` varchar(20) NOT NULL, + `age` int(2) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; + +-- ---------------------------- +-- Records of user_info +-- ---------------------------- +INSERT INTO `user_info` VALUES ('1', 'xiaour', '25'); + diff --git a/README.md b/README.md deleted file mode 100644 index ae7616d..0000000 --- a/README.md +++ /dev/null @@ -1,56 +0,0 @@ -## 相关文章 - -1.[SpringMVC配置太多?试试SpringBoot](https://xiaour.github.io/2018/05/02/The_SpringMVC_configuration_is_too_much_Try_SpringBoot/) - -2.[Springboot集成Kafka](https://xiaour.github.io/2018/05/23/Springboot_integrated_Kafka/) - -3.[Springboot集成RocketMQ](https://xiaour.github.io/2018/08/16/SpringbootRocketMQ/) - -4.Webflux Spring异步编程,你将发现新大陆(代码已经部分上传,blog完善中...) - -5.[利用EasyExcel,两行代码开发一个和API结果一致的生成Excel功能](https://github.com/xiaour/EasyExport#readme) - -## 代码部分 - -⭐️ SpringBootDemo -本代码集成了SpringBoot+MyBatis+Redis+MySql。 -最新的部分经网友指正已经把冗余的代码去掉了,代码部分和配置文件部分都有相关的注释; -git clone 到本地后就可以运行了,项目中使用到的数据库表如下 - -```sql --- ---------------------------- --- Table structure for `user_info` --- ---------------------------- -DROP TABLE IF EXISTS `user_info`; -CREATE TABLE `user_info` ( - `id` int(8) NOT NULL AUTO_INCREMENT, - `name` varchar(20) NOT NULL, - `age` int(2) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; - --- ---------------------------- --- Records of user_info --- ---------------------------- -INSERT INTO `user_info` VALUES ('1', 'xiaour', '18'); -``` - -⭐️ SpringBootDemoV2 -代码主要和SpringBootDemo的区别是使用了Springboot2.0 - -2018.08.22 添加了Twitter ID生成算法的工具,每秒支持12万ID生成。 - -⭐️ SpringBootKafkaDemo -Springboot2.0继承了Kafka消息中间件 - -⭐️ SpringBootRocketMqDemo -Springboot2.0继承了RocketMQ4.3消息中间件 - -⭐️ SpringWebfluxDemo -Webflux Spring异步编程。 - - ---------------------------------- -有兴趣的朋友可以关注一下最新开源的 -[spring.boot.sapi.starter](https://github.com/xiaour/spring.boot.sapi.starter) - diff --git a/SpringBootDemo/com.tony.spring.boot.iml b/SpringBootDemo/com.tony.spring.boot.iml new file mode 100644 index 0000000..0a062f2 --- /dev/null +++ b/SpringBootDemo/com.tony.spring.boot.iml @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootDemo/pom.xml b/SpringBootDemo/pom.xml index 3280d80..877e7ca 100644 --- a/SpringBootDemo/pom.xml +++ b/SpringBootDemo/pom.xml @@ -4,20 +4,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.github.xiaour - springbootv1 - 0.0.1-SNAPSHOT - SpringBootDemo - Demo project for Spring Boot - jar - - + com.tony + com.tony.spring.boot + 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE - @@ -99,13 +93,13 @@ com.alibaba fastjson - 1.2.83 + 1.2.31 commons-io commons-io - 2.7 + 2.5 @@ -116,25 +110,8 @@ org.apache.httpcomponents httpmime - - - - - org.apache.poi - poi - 4.1.1 - - - org.apache.poi - poi-ooxml - 3.13 - - - org.apache.poi - ooxml-schemas - 1.1 - - + + diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java index ba66900..db70642 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/Application.java @@ -1,45 +1,46 @@ -package com.xiaour.spring.boot; - -import org.mybatis.spring.annotation.MapperScan; -import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; -import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; -import org.springframework.boot.web.servlet.ServletComponentScan; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -/** - * - * @ClassName Application - * @author Zhang.Tao - * @Date 2017年4月27日 下午5:30:34 - * @version V2.0.0 - */ - -@SpringBootApplication(exclude = MybatisAutoConfiguration.class) -@ServletComponentScan -@MapperScan("com.xiaour.spring.boot.mapper") -public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { - - @Value("${server.port}") - private int port;//应用的端口 - /** - * 启动入口 - * @param args - */ - public static void main(String ... args){ - SpringApplication.run(Application.class, args); - } - - /** - * 自定义端口 - */ - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(port); - } - -} +package com.xiaour.spring.boot; + +import org.mybatis.spring.annotation.MapperScan; +import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; +import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +/** + * + * @ClassName Application + * @author Zhang.Tao + * @Date 2017年4月27日 下午5:30:34 + * @version V2.0.0 + */ + +@SpringBootApplication(exclude = MybatisAutoConfiguration.class) +@ServletComponentScan +@EnableAutoConfiguration +@MapperScan("com.xiaour.spring.boot.mapper") +public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { + + @Value("${server.port}") + private int port;//应用的端口 + /** + * 启动入口 + * @param args + */ + public static void main(String ... args){ + SpringApplication.run(Application.class, args); + } + + /** + * 自定义端口 + */ + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + container.setPort(port); + } + +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MyBatisConfig.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MyBatisConfig.java deleted file mode 100644 index 5b1f78d..0000000 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/config/MyBatisConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.xiaour.spring.boot.config; - -import com.alibaba.druid.pool.DruidDataSource; -import org.apache.ibatis.session.SqlSessionFactory; -import org.mybatis.spring.SqlSessionFactoryBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; - - -/** - * @Date: 2018-12-26 12:05 - * @version: v1.0 - * @Description: mybatis stater从某个版本后去掉了自动配置,需要用config配置 - */ -@Configuration -public class MyBatisConfig { - - @Autowired - private DataSourceProperties dataSourceProperties; - - - @Bean(name = "dataSource") - public DruidDataSource dataSource() { - DruidDataSource dataSource = new DruidDataSource(); - dataSource.setUrl(dataSourceProperties.getUrl()); - - dataSource.setDriverClassName(dataSourceProperties.getDriverClassName()); - dataSource.setUsername(dataSourceProperties.getUsername()); - dataSource.setPassword(dataSourceProperties.getPassword()); - - return dataSource; - - } - - @Bean - public SqlSessionFactory sqlSessionFactory() throws Exception { - SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); - sqlSessionFactoryBean.setDataSource(dataSource()); - sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() - .getResources(("classpath*:mapper/*.xml"))); - return sqlSessionFactoryBean.getObject(); - } -} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java index d7d1807..a31bf00 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/controller/TestCtrl.java @@ -3,8 +3,6 @@ import com.xiaour.spring.boot.service.RedisService; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.LocalVariableTableParameterNameDiscoverer; -import org.springframework.core.ParameterNameDiscoverer; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -13,11 +11,6 @@ import com.xiaour.spring.boot.mapper.UserInfoMapper; import com.xiaour.spring.boot.utils.JsonUtil; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Created by xiaour on 2017/4/19. @@ -80,63 +73,7 @@ public String get(@PathVariable("id")int id){ e.printStackTrace(); } return ""; - } - - - public static void main(String[] args) { - Map keyMap= new HashMap<>(); - keyMap.put("id","编号"); - keyMap.put("name","名称"); - - String [] cnCloumn={"编号","名称"}; - - System.out.println(Arrays.asList(convertMap(keyMap, cnCloumn))); - - } - - public static String[] convertMap(Map keyMap,String [] dataList){ - - for(int i=0;i m:keyMap.entrySet()){ - if(m.getValue().equals(dataList[i])){ - dataList[i]=m.getKey(); - } - } - } - - return dataList; - } - - - public static String getName(String name,String add){ - return null; - } - - public static void testGetClassName() { - // 方法1:通过SecurityManager的保护方法getClassContext() - String clazzName = new SecurityManager() { - public String getClassName() { - return getClassContext()[1].getName(); - } - }.getClassName(); - System.out.println(clazzName); - // 方法2:通过Throwable的方法getStackTrace() - String clazzName2 = new Throwable().getStackTrace()[1].getClassName(); - System.out.println(clazzName2); - // 方法3:通过分析匿名类名称() - String clazzName3 = new Object() { - public String getClassName() { - String clazzName = this.getClass().getName(); - return clazzName.substring(0, clazzName.lastIndexOf('$')); - } - }.getClassName(); - System.out.println(clazzName3); - //方法4:通过Thread的方法getStackTrace() - String clazzName4 = Thread.currentThread().getStackTrace()[2].getClassName(); - System.out.println(clazzName4); - } - - + } + } diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java new file mode 100644 index 0000000..f279b8e --- /dev/null +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/exception/DingTalkEncryptException.java @@ -0,0 +1,53 @@ +package com.xiaour.spring.boot.exception; + +import java.util.HashMap; +import java.util.Map; + +/** + * 钉钉开放平台加解密异常类 + */ +public class DingTalkEncryptException extends Exception { + /**成功**/ + public static final int SUCCESS = 0; + /**加密明文文本非法**/ + public final static int ENCRYPTION_PLAINTEXT_ILLEGAL = 900001; + /**加密时间戳参数非法**/ + public final static int ENCRYPTION_TIMESTAMP_ILLEGAL = 900002; + /**加密随机字符串参数非法**/ + public final static int ENCRYPTION_NONCE_ILLEGAL = 900003; + /**不合法的aeskey**/ + public final static int AES_KEY_ILLEGAL = 900004; + /**签名不匹配**/ + public final static int SIGNATURE_NOT_MATCH = 900005; + /**计算签名错误**/ + public final static int COMPUTE_SIGNATURE_ERROR = 900006; + /**计算加密文字错误**/ + public final static int COMPUTE_ENCRYPT_TEXT_ERROR = 900007; + /**计算解密文字错误**/ + public final static int COMPUTE_DECRYPT_TEXT_ERROR = 900008; + /**计算解密文字长度不匹配**/ + public final static int COMPUTE_DECRYPT_TEXT_LENGTH_ERROR = 900009; + /**计算解密文字corpid不匹配**/ + public final static int COMPUTE_DECRYPT_TEXT_CORPID_ERROR = 900010; + + private static Map msgMap = new HashMap(); + static{ + msgMap.put(SUCCESS,"成功"); + msgMap.put(ENCRYPTION_PLAINTEXT_ILLEGAL,"加密明文文本非法"); + msgMap.put(ENCRYPTION_TIMESTAMP_ILLEGAL,"加密时间戳参数非法"); + msgMap.put(ENCRYPTION_NONCE_ILLEGAL,"加密随机字符串参数非法"); + msgMap.put(SIGNATURE_NOT_MATCH,"签名不匹配"); + msgMap.put(COMPUTE_SIGNATURE_ERROR,"签名计算失败"); + msgMap.put(AES_KEY_ILLEGAL,"不合法的aes key"); + msgMap.put(COMPUTE_ENCRYPT_TEXT_ERROR,"计算加密文字错误"); + msgMap.put(COMPUTE_DECRYPT_TEXT_ERROR,"计算解密文字错误"); + msgMap.put(COMPUTE_DECRYPT_TEXT_LENGTH_ERROR,"计算解密文字长度不匹配"); + msgMap.put(COMPUTE_DECRYPT_TEXT_CORPID_ERROR,"计算解密文字corpid或者suiteKey不匹配"); + } + + public Integer code; + public DingTalkEncryptException(Integer exceptionCode){ + super(msgMap.get(exceptionCode)); + this.code = exceptionCode; + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java index 50cb43f..9850a58 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/mapper/UserInfoMapper.java @@ -1,13 +1,9 @@ -package com.xiaour.spring.boot.mapper; - -import com.xiaour.spring.boot.entity.UserInfo; -import org.apache.ibatis.annotations.Mapper; -import org.springframework.stereotype.Component; - -@Component -@Mapper -public interface UserInfoMapper { - - UserInfo selectByPrimaryKey(Integer id); - +package com.xiaour.spring.boot.mapper; + +import com.xiaour.spring.boot.entity.UserInfo; + +public interface UserInfoMapper { + + UserInfo selectByPrimaryKey(Integer id); + } \ No newline at end of file diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/RedisService.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/RedisService.java index e08e182..bd8d4f6 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/RedisService.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/RedisService.java @@ -1,35 +1,35 @@ -package com.xiaour.spring.boot.service; - -import java.util.List; - -/** - * Created by zhangtao on 2017/11/8. - */ - -public interface RedisService { - - boolean set(String key, String value) throws Exception; - - String get(String key) throws Exception; - - boolean expire(String key, long expire) throws Exception; - - boolean setList(String key, List list) throws Exception; - - List getList(String key, Class clz) throws Exception; - - long lpush(String key, Object obj) throws Exception; - - long rpush(String key, Object obj) throws Exception; - - void hmset(String key, Object obj) throws Exception; - - T hget(String key, Class clz) throws Exception; - - - void del(String key) throws Exception; - - List hmGetAll(String key, Class clz) throws Exception; - - String lpop(String key) throws Exception; -} +package com.xiaour.spring.boot.service; + +import java.util.List; + +/** + * Created by zhangtao on 2017/11/8. + */ + +public interface RedisService { + + boolean set(String key, String value) throws Exception; + + String get(String key) throws Exception; + + boolean expire(String key, long expire) throws Exception; + + boolean setList(String key, List list) throws Exception; + + List getList(String key, Class clz) throws Exception; + + long lpush(String key, Object obj) throws Exception; + + long rpush(String key, Object obj) throws Exception; + + void hmset(String key, Object obj) throws Exception; + + T hget(String key, Class clz) throws Exception; + + + void del(String key) throws Exception; + + List hmGetAll(String key, Class clz) throws Exception; + + String lpop(String key) throws Exception; +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/impl/RedisServiceImpl.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/impl/RedisServiceImpl.java index 3f451d2..edadae1 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/impl/RedisServiceImpl.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/service/impl/RedisServiceImpl.java @@ -1,208 +1,208 @@ -package com.xiaour.spring.boot.service.impl; - - -import com.xiaour.spring.boot.service.RedisService; -import com.xiaour.spring.boot.utils.JsonUtil; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.data.redis.connection.RedisConnection; -import org.springframework.data.redis.core.RedisCallback; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.Assert; - -import java.util.*; -import java.util.concurrent.TimeUnit; - -/** - * Created by xiaour.github.com on 2017/11/8. - */ -@Service("redisService") -@Transactional(rollbackFor = Exception.class) -public class RedisServiceImpl implements RedisService { - - private static int seconds=3600*24; - - @Autowired - private RedisTemplate redisTemplate; - - @Override - public boolean set(final String key, final String value) throws Exception { - Assert.hasText(key,"Key is not empty."); - boolean result = redisTemplate.execute(new RedisCallback() { - @Override - public Boolean doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - connection.set(serializer.serialize(key), serializer.serialize(value)); - return true; - } - }); - return result; - } - - public String get(final String key) throws Exception { - Assert.hasText(key,"Key is not empty."); - String result = redisTemplate.execute(new RedisCallback() { - @Override - public String doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - byte[] value = connection.get(serializer.serialize(key)); - return serializer.deserialize(value); - } - }); - return result; - } - - public void del(final String key) throws Exception { - Assert.hasText(key,"Key is not empty."); - - redisTemplate.execute(new RedisCallback() { - @Override - public Long doInRedis(RedisConnection conn) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - return conn.del(serializer.serialize(key)); - } - }); - } - - - - @Override - public boolean expire(final String key, long expire) { - return redisTemplate.expire(key, expire, TimeUnit.SECONDS); - } - - @Override - public boolean setList(String key, List list) throws Exception { - Assert.hasText(key,"Key is not empty."); - - String value = JsonUtil.getJsonString(list); - return set(key,value); - } - - @Override - public List getList(String key,Class clz) throws Exception{ - - Assert.hasText(key,"Key is not empty."); - - String json = get(key); - if(json!=null){ - List list = JsonUtil.readJson2Array(json,clz); - return list; - } - return null; - } - - @Override - public long lpush(final String key, Object obj)throws Exception { - Assert.hasText(key,"Key is not empty."); - - final String value = JsonUtil.getJsonString(obj); - long result = redisTemplate.execute(new RedisCallback() { - @Override - public Long doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - long count = connection.lPush(serializer.serialize(key), serializer.serialize(value)); - return count; - } - }); - return result; - } - - @Override - public long rpush(final String key, Object obj) throws Exception{ - Assert.hasText(key,"Key is not empty."); - - final String value = JsonUtil.getJsonString(obj); - long result = redisTemplate.execute(new RedisCallback() { - @Override - public Long doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - long count = connection.rPush(serializer.serialize(key), serializer.serialize(value)); - return count; - } - }); - return result; - } - - @Override - public void hmset(String key, Object obj) throws Exception{ - Assert.hasText(key,"Key is not empty."); - - Map data=JsonUtil.readJsonByteMap(JsonUtil.getJsonString(obj)); - redisTemplate.execute(new RedisCallback() { - @Override - public String doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - connection.hMSet(serializer.serialize(key),data); - return ""; - } - }); - } - - @Override - public T hget(String key, Class clz) throws Exception{ - Assert.hasText(key,"Key is not empty."); - - return redisTemplate.execute(new RedisCallback() { - - @Override - public T doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - - Map result; - - Map data=connection.hGetAll(serializer.serialize(key)); - result= new HashMap<>(); - for (Map.Entry entry: data.entrySet()) { - result.put(serializer.deserialize(entry.getKey()),serializer.deserialize(entry.getValue())); - } - - return JsonUtil.json2Obj(JsonUtil.getJsonString(result),clz); - } - }); - } - - @Override - public List hmGetAll(String key,Class clz) throws Exception{ - Assert.hasText(key,"Key is not empty."); - - List> dataList= new ArrayList<>(); - return redisTemplate.execute(new RedisCallback>() { - @Override - public List doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - - Set keysSet=redisTemplate.keys(key); - Map data; - Map result; - for(String newKey:keysSet) { - data=connection.hGetAll(serializer.serialize(newKey)); - result= new HashMap<>(); - for (Map.Entry entry: data.entrySet()) { - result.put(serializer.deserialize(entry.getKey()),serializer.deserialize(entry.getValue())); - } - dataList.add(result); - } - return JsonUtil.readJson2Array(JsonUtil.getJsonString(dataList),clz); - } - }); - } - - @Override - public String lpop(final String key) throws Exception{ - Assert.hasText(key,"Key is not empty."); - - String result = redisTemplate.execute(new RedisCallback() { - @Override - public String doInRedis(RedisConnection connection) throws DataAccessException { - RedisSerializer serializer = redisTemplate.getStringSerializer(); - byte[] res = connection.lPop(serializer.serialize(key)); - return serializer.deserialize(res); - } - }); - return result; - } -} +package com.xiaour.spring.boot.service.impl; + + +import com.xiaour.spring.boot.service.RedisService; +import com.xiaour.spring.boot.utils.JsonUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; + +import java.util.*; +import java.util.concurrent.TimeUnit; + +/** + * Created by xiaour.github.com on 2017/11/8. + */ +@Service("redisService") +@Transactional(rollbackFor = Exception.class) +public class RedisServiceImpl implements RedisService { + + private static int seconds=3600*24; + + @Autowired + private RedisTemplate redisTemplate; + + @Override + public boolean set(final String key, final String value) throws Exception { + Assert.hasText(key,"Key is not empty."); + boolean result = redisTemplate.execute(new RedisCallback() { + @Override + public Boolean doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + connection.set(serializer.serialize(key), serializer.serialize(value)); + return true; + } + }); + return result; + } + + public String get(final String key) throws Exception { + Assert.hasText(key,"Key is not empty."); + String result = redisTemplate.execute(new RedisCallback() { + @Override + public String doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + byte[] value = connection.get(serializer.serialize(key)); + return serializer.deserialize(value); + } + }); + return result; + } + + public void del(final String key) throws Exception { + Assert.hasText(key,"Key is not empty."); + + redisTemplate.execute(new RedisCallback() { + @Override + public Long doInRedis(RedisConnection conn) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + return conn.del(serializer.serialize(key)); + } + }); + } + + + + @Override + public boolean expire(final String key, long expire) { + return redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + + @Override + public boolean setList(String key, List list) throws Exception { + Assert.hasText(key,"Key is not empty."); + + String value = JsonUtil.getJsonString(list); + return set(key,value); + } + + @Override + public List getList(String key,Class clz) throws Exception{ + + Assert.hasText(key,"Key is not empty."); + + String json = get(key); + if(json!=null){ + List list = JsonUtil.readJson2Array(json,clz); + return list; + } + return null; + } + + @Override + public long lpush(final String key, Object obj)throws Exception { + Assert.hasText(key,"Key is not empty."); + + final String value = JsonUtil.getJsonString(obj); + long result = redisTemplate.execute(new RedisCallback() { + @Override + public Long doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + long count = connection.lPush(serializer.serialize(key), serializer.serialize(value)); + return count; + } + }); + return result; + } + + @Override + public long rpush(final String key, Object obj) throws Exception{ + Assert.hasText(key,"Key is not empty."); + + final String value = JsonUtil.getJsonString(obj); + long result = redisTemplate.execute(new RedisCallback() { + @Override + public Long doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + long count = connection.rPush(serializer.serialize(key), serializer.serialize(value)); + return count; + } + }); + return result; + } + + @Override + public void hmset(String key, Object obj) throws Exception{ + Assert.hasText(key,"Key is not empty."); + + Map data=JsonUtil.readJsonByteMap(JsonUtil.getJsonString(obj)); + redisTemplate.execute(new RedisCallback() { + @Override + public String doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + connection.hMSet(serializer.serialize(key),data); + return ""; + } + }); + } + + @Override + public T hget(String key, Class clz) throws Exception{ + Assert.hasText(key,"Key is not empty."); + + return redisTemplate.execute(new RedisCallback() { + + @Override + public T doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + + Map result; + + Map data=connection.hGetAll(serializer.serialize(key)); + result= new HashMap<>(); + for (Map.Entry entry: data.entrySet()) { + result.put(serializer.deserialize(entry.getKey()),serializer.deserialize(entry.getValue())); + } + + return JsonUtil.json2Obj(JsonUtil.getJsonString(result),clz); + } + }); + } + + @Override + public List hmGetAll(String key,Class clz) throws Exception{ + Assert.hasText(key,"Key is not empty."); + + List> dataList= new ArrayList<>(); + return redisTemplate.execute(new RedisCallback>() { + @Override + public List doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + + Set keysSet=redisTemplate.keys(key); + Map data; + Map result; + for(String newKey:keysSet) { + data=connection.hGetAll(serializer.serialize(newKey)); + result= new HashMap<>(); + for (Map.Entry entry: data.entrySet()) { + result.put(serializer.deserialize(entry.getKey()),serializer.deserialize(entry.getValue())); + } + dataList.add(result); + } + return JsonUtil.readJson2Array(JsonUtil.getJsonString(dataList),clz); + } + }); + } + + @Override + public String lpop(final String key) throws Exception{ + Assert.hasText(key,"Key is not empty."); + + String result = redisTemplate.execute(new RedisCallback() { + @Override + public String doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer serializer = redisTemplate.getStringSerializer(); + byte[] res = connection.lPop(serializer.serialize(key)); + return serializer.deserialize(res); + } + }); + return result; + } +} diff --git a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java index 66be6e2..d392db9 100644 --- a/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java +++ b/SpringBootDemo/src/main/java/com/xiaour/spring/boot/utils/JsonUtil.java @@ -1,83 +1,89 @@ -package com.xiaour.spring.boot.utils; - -import com.google.gson.*; -import com.google.gson.reflect.TypeToken; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class JsonUtil { - - private static Gson gson = null; - - static{ - gson = new Gson(); - } - - public static synchronized Gson newInstance(){ - if(gson == null){ - gson = new Gson(); - } - return gson; - } - - public static String getJsonString(Object obj){ - return gson.toJson(obj); - } - - public static T toBean(String json,Class clz){ - - return gson.fromJson(json, clz); - } - - public static Map readJson2MapObj(String json,Class clz){ - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map result = new HashMap<>(); - for(String key:map.keySet()){ - result.put(key,gson.fromJson(map.get(key),clz) ); - } - return result; - } - - public static T json2Obj(String json,Class clz){ - return gson.fromJson(json,clz); - } - - public static Map toMap(String json){ - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - return map; - } - - public static Map readJsonStrMap(String json) { - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map result = new HashMap<>(); - for(String key:map.keySet()){ - result.put(key,gson.fromJson(map.get(key),String.class) ); - } - return result; - } - - public static Map readJsonByteMap(String json) { - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map vmap = new HashMap<>(); - for(String key:map.keySet()){ - vmap.put(key.getBytes(),gson.fromJson(map.get(key),String.class).getBytes() ); - } - return vmap; - - } - - - public static List readJson2Array(String json, Class clz){ - JsonArray array = new JsonParser().parse(json).getAsJsonArray(); - List list = new ArrayList<>(); - for(final JsonElement elem : array){ - list.add(gson.fromJson(elem, (Type)clz)); - } - return list; - } - +package com.xiaour.spring.boot.utils; + +import com.google.gson.*; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class JsonUtil { + + private static Gson gson = null; + + static{ + gson = new Gson(); + } + + public static synchronized Gson newInstance(){ + if(gson == null){ + gson = new Gson(); + } + return gson; + } + + public static String getJsonString(Object obj){ + return gson.toJson(obj); + } + + public static T toBean(String json,Class clz){ + + return gson.fromJson(json, clz); + } + + public static Map readJson2MapObj(String json,Class clz){ + Map map = gson.fromJson(json, new TypeToken>(){}.getType()); + Map result = new HashMap<>(); + for(String key:map.keySet()){ + result.put(key,gson.fromJson(map.get(key),clz) ); + } + return result; + } + + public static T json2Obj(String json,Class clz){ + return gson.fromJson(json,clz); + } + + public static Map toMap(String json){ + Map map = gson.fromJson(json, new TypeToken>(){}.getType()); + return map; + } + + public static Map readJsonStrMap(String json) { + Map map = gson.fromJson(json, new TypeToken>(){}.getType()); + Map result = new HashMap<>(); + for(String key:map.keySet()){ + result.put(key,gson.fromJson(map.get(key),String.class) ); + } + return result; + } + + public static Map readJsonByteMap(String json) { + Map map = gson.fromJson(json, new TypeToken>(){}.getType()); + Map vmap = new HashMap<>(); + for(String key:map.keySet()){ + vmap.put(key.getBytes(),gson.fromJson(map.get(key),String.class).getBytes() ); + } + return vmap; + + } + + + public static List readJson2Array(String json, Class clz){ + JsonArray array = new JsonParser().parse(json).getAsJsonArray(); + List list = new ArrayList<>(); + for(final JsonElement elem : array){ + list.add(gson.fromJson(elem, (Type)clz)); + } + return list; + } + + + public static void main(String[] args) { + String json="{\"snapshots\":[{\"snapshot\":\"snapshot_129\",\"uuid\":\"kaM9ip2GQoCsT3wn38OcsQ\",\"version_id\":5040399,\"version\":\"5.4.3\",\"indices\":[\"metricbeat-2018.01.04\",\"metricbeat-2018.01.03\",\"metricbeat-2017.12.11\",\"metricbeat-2017.12.23\",\"metricbeat-2018.01.29\",\"metricbeat-2017.12.17\",\"metricbeat-2017.12.05\",\"metricbeat-2018.01.26\",\"metricbeat-2017.12.16\",\"metricbeat-2017.12.30\",\"metricbeat-2017.12.29\"],\"state\":\"SUCCESS\",\"duration_in_millis\":4310,\"failures\":[],\"shards\":{\"total\":321,\"failed\":0,\"successful\":321}}]}"; + + System.out.println(toMap(json)); + } } \ No newline at end of file diff --git a/SpringBootDemo/src/main/resources/application.yml b/SpringBootDemo/src/main/resources/application.yml index 167b873..b1fe622 100644 --- a/SpringBootDemo/src/main/resources/application.yml +++ b/SpringBootDemo/src/main/resources/application.yml @@ -1,39 +1,52 @@ -#服务启动端口 -server : - port : 8080 - -#数据库配置 -spring: - datasource: - url: jdbc:mysql://127.0.0.1:9966/study?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&useSSL=false&verifyServerCertificate=false - username: your.account - password: your.pass - # 使用druid数据源 - type: com.alibaba.druid.pool.DruidDataSource - driver-class-name: com.mysql.jdbc.Driver - redis: - host: 127.0.0.1 - #redis密码,没有密码的可以用~表示 - password: ~ - port: 6379 - pool: - max-active: 100 - max-idle: 10 - max-wait: 100000 -# Mybatis mapper 映射路径配置 -mybatis: - type-aliases-package: com.xiaour.spring.boot.mapper - mapper-locations: classpath*:mapper/*.xml - configLocation: classpath:mybatis-config.xml - -# 日志输出 -logging: - file: D:/boot.log - level: - com.ibatis:DEBUG - root:DEBUG - -task: - cron:0 0/5 * * * ? - - +#服务启动端口 +server : + port : 8080 + +#数据库配置 +spring: + datasource: + name: test + url: jdbc:mysql://192.168.2.5:3335/test_data?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true&useSSL=false&zeroDateTimeBehavior=convertToNull + username: root + password: chifaner159 + # 使用druid数据源 + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.jdbc.Driver + filters: stat + maxActive: 20 + initialSize: 1 + maxWait: 60000 + minIdle: 1 + timeBetweenEvictionRunsMillis: 60000 + minEvictableIdleTimeMillis: 300000 + validationQuery: select 'x' + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + poolPreparedStatements: true + maxOpenPreparedStatements: 20 + redis: + host: 192.168.2.5 + #redis密码,没有密码的可以用~表示 + password: ~ + port: 6381 + pool: + max-active: 100 + max-idle: 10 + max-wait: 100000 +mybatis: + type-aliases-package: com.xiaour.spring.boot.mapper + mapper-locations: classpath:mapper/*.xml + configLocation: classpath:mybatis-config.xml + +# 日志输出 +logging: + file: D:/boot.log + level: + com.ibatis:DEBUG + root:DEBUG + +task: + cron:0 0/5 * * * ? + + diff --git a/SpringBootDemo/src/main/resources/mapper/UserInfoMapper.xml b/SpringBootDemo/src/main/resources/mapper/UserInfoMapper.xml index 563ff4a..ab99026 100644 --- a/SpringBootDemo/src/main/resources/mapper/UserInfoMapper.xml +++ b/SpringBootDemo/src/main/resources/mapper/UserInfoMapper.xml @@ -1,19 +1,19 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SpringBootDemoV2/.gitignore b/SpringBootDemoV2/.gitignore deleted file mode 100644 index 2af7cef..0000000 --- a/SpringBootDemoV2/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -nbproject/private/ -build/ -nbbuild/ -dist/ -nbdist/ -.nb-gradle/ \ No newline at end of file diff --git a/SpringBootDemoV2/pom.xml b/SpringBootDemoV2/pom.xml deleted file mode 100644 index 9c0856a..0000000 --- a/SpringBootDemoV2/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - 4.0.0 - - com.github.xiaour - springbootv2 - 0.0.1-SNAPSHOT - SpringBootDemoV2 - Demo project for Spring Boot V2 - jar - - - - org.springframework.boot - spring-boot-starter-parent - 2.4.2 - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - org.springframework.boot - spring-boot-starter-web - - - - com.alibaba.boot - dubbo-spring-boot-starter - 0.1.0 - - - - org.apache.zookeeper - zookeeper - 3.7.2 - - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.code.gson - gson - 2.8.9 - - - - commons-codec - commons-codec - 1.10 - - - - junit - junit - 4.13.1 - - - - org.jodd - jodd-http - 3.7.1 - - - - org.apache.httpcomponents - httpclient - - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/Application.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/Application.java deleted file mode 100644 index caf30a9..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/Application.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.github.xiaour; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - - -@SpringBootApplication -public class Application { - - - - public static void main(String[] args) { - //SpringApplication.run(Application.class, args); - - - } - - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/config/DuckPorperties.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/config/DuckPorperties.java deleted file mode 100644 index 2f722f6..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/config/DuckPorperties.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.github.xiaour.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/3/1 下午5:04 - */ -@Configuration -@ConfigurationProperties(prefix="duck") -public class DuckPorperties{ - - private String duckName; - - private int totalCount; - - public String getDuckName() { - return duckName; - } - - public void setDuckName(String duckName) { - this.duckName = duckName; - } - - public int getTotalCount() { - return totalCount; - } - - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/constants/Api.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/constants/Api.java deleted file mode 100644 index 6bd8fb1..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/constants/Api.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.github.xiaour.constants; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/3/13 上午10:09 - */ -public class Api { - - /** - * 获取第三方平台component_access_token - */ - public static final String component_token="https://api.weixin.qq.com/cgi-bin/component/api_component_token"; - - /** - * 获取预授权码pre_auth_code - */ - public static final String create_preauthcode="https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token="; - - /** - * 使用授权码换取公众号或小程序的接口调用凭据和授权信息 - */ - public static final String query_auth="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token="; - - /** - * 获取(刷新)授权公众号或小程序的接口调用凭据(令牌) - */ - public static final String authorizer_token="https:// api.weixin.qq.com /cgi-bin/component/api_authorizer_token?component_access_token="; - - /** - * 获取授权方的帐号基本信息 - */ - public static final String get_authorizer_info="https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token="; - - /** - * 获取授权方的选项设置信息 - */ - public static final String get_authorizer_option="https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token="; - - /** - * 设置授权方的选项信息 - */ - public static final String set_authorizer_option="https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token="; - - - enum Type{ - A; - } - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/controller/DemoController.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/controller/DemoController.java deleted file mode 100644 index 27c6ccd..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/controller/DemoController.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.github.xiaour.controller; - -import com.github.xiaour.config.DuckPorperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/3/1 下午4:54 - */ -@RestController -public class DemoController { - @Autowired - private DuckPorperties duckPorperties; - - @RequestMapping("/amazing") - public Map amazing() { - /** - * 如果不需要其他的结构,可以直接返回对象类型,不必要强制JSON格式。Springboot默认支持转为json - */ - Map obj= new HashMap<>(); - obj.put("name","xiaour"); - obj.put("age","18"); - obj.put("age","18"); - return obj; - } - - @RequestMapping("/duck") - public String duck() { - /** - * 自动装配模式的配置文件属性。 - */ - return duckPorperties.getDuckName(); - } - - - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/AesException.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/AesException.java deleted file mode 100755 index 0014bbc..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/AesException.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.github.xiaour.exception; - -@SuppressWarnings("serial") -public class AesException extends Exception { - - public final static int OK = 0; - public final static int ValidateSignatureError = -40001; - public final static int ParseXmlError = -40002; - public final static int ComputeSignatureError = -40003; - public final static int IllegalAesKey = -40004; - public final static int ValidateAppidError = -40005; - public final static int EncryptAESError = -40006; - public final static int DecryptAESError = -40007; - public final static int IllegalBuffer = -40008; - //public final static int EncodeBase64Error = -40009; - //public final static int DecodeBase64Error = -40010; - //public final static int GenReturnXmlError = -40011; - - private int code; - - private static String getMessage(int code) { - switch (code) { - case ValidateSignatureError: - return "签名验证错误"; - case ParseXmlError: - return "xml解析失败"; - case ComputeSignatureError: - return "sha加密生成签名失败"; - case IllegalAesKey: - return "SymmetricKey非法"; - case ValidateAppidError: - return "appid校验失败"; - case EncryptAESError: - return "aes加密失败"; - case DecryptAESError: - return "aes解密失败"; - case IllegalBuffer: - return "解密后得到的buffer非法"; -// case EncodeBase64Error: -// return "base64加密错误"; -// case DecodeBase64Error: -// return "base64解密错误"; -// case GenReturnXmlError: -// return "xml生成失败"; - default: - return null; // cannot be - } - } - - public int getCode() { - return code; - } - - public AesException(int code) { - super(getMessage(code)); - this.code = code; - } - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/OApiException.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/OApiException.java deleted file mode 100644 index e037c5d..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/exception/OApiException.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.github.xiaour.exception; - -import java.io.IOException; - -public class OApiException extends Exception { - - /** - */ - private static final long serialVersionUID = 1L; - - public OApiException(int errCode, String errMsg) { - super("error code: " + errCode + ", error message: " + errMsg); - } - - public OApiException(IOException e) { - super(e); - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/service/DubboService.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/service/DubboService.java deleted file mode 100644 index 61f0354..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/service/DubboService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.github.xiaour.service; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/4/25 16:57 - */ - -public interface DubboService { - - String hello(String name); - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/service/impl/DubboServiceImpl.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/service/impl/DubboServiceImpl.java deleted file mode 100644 index b6c8cf1..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/service/impl/DubboServiceImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.github.xiaour.service.impl; - -import com.alibaba.dubbo.config.annotation.Service; -import com.github.xiaour.service.DubboService; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/4/25 16:59 - */ - - -@Service( - version = "1.0.0", - application = "${dubbo.application.id}", - protocol = "${dubbo.protocol.id}", - registry = "${dubbo.registry.id}" -) -public class DubboServiceImpl implements DubboService { - @Override - public String hello(String name) { - return "Hello,"+name; - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/ByteGroup.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/ByteGroup.java deleted file mode 100755 index 142d90d..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/ByteGroup.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.github.xiaour.utils; - -import java.util.ArrayList; - -class ByteGroup { - ArrayList byteContainer = new ArrayList(); - - public byte[] toBytes() { - byte[] bytes = new byte[byteContainer.size()]; - for (int i = 0; i < byteContainer.size(); i++) { - bytes[i] = byteContainer.get(i); - } - return bytes; - } - - public ByteGroup addBytes(byte[] bytes) { - for (byte b : bytes) { - byteContainer.add(b); - } - return this; - } - - public int size() { - return byteContainer.size(); - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/HttpHelper.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/HttpHelper.java deleted file mode 100644 index 9a5b791..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/HttpHelper.java +++ /dev/null @@ -1,219 +0,0 @@ -package com.github.xiaour.utils; - - - -import com.github.xiaour.constants.Api; -import com.github.xiaour.exception.OApiException; -import com.google.gson.JsonObject; -import org.apache.http.HttpEntity; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.util.EntityUtils; -import org.springframework.web.client.RestTemplate; - -import java.io.IOException; -import java.util.Map; - - -public class HttpHelper { - - - private static RestTemplate restTemplate = new RestTemplate(); - - private static JsonObject jsonObject = null; - - static{ - jsonObject = new JsonObject(); - } - - public static synchronized JsonObject instance(){ - if(jsonObject == null){ - jsonObject = new JsonObject(); - } - return jsonObject; - } - - - public static JsonObject httpGet(String url) throws OApiException { - HttpGet httpGet = new HttpGet(url); - CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - RequestConfig requestConfig = RequestConfig.custom(). - setSocketTimeout(10000).setConnectTimeout(10000).build(); - httpGet.setConfig(requestConfig); - - try { - response = httpClient.execute(httpGet, new BasicHttpContext()); - - if (response.getStatusLine().getStatusCode() != 200) { - return null; - } - HttpEntity entity = response.getEntity(); - if (entity != null) { - String resultStr = EntityUtils.toString(entity, "utf-8"); - return jsonObject.getAsJsonObject(resultStr); - - } - } catch (IOException e) { - throw new OApiException(e); - } finally { - if (response != null) try { - response.close(); - } catch (IOException e) { - throw new OApiException(e); - } - } - - return null; - } - - - public static String postXmlStr(String url,String xmlStr) throws OApiException { - HttpPost httpPost = new HttpPost(url); - CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - RequestConfig requestConfig = RequestConfig.custom(). - setSocketTimeout(10000).setConnectTimeout(10000).build(); - httpPost.setConfig(requestConfig); - httpPost.addHeader("Content-Type", "application/xml"); - try { - StringEntity requestEntity = new StringEntity(xmlStr, "utf-8"); - httpPost.setEntity(requestEntity); - - response = httpClient.execute(httpPost, new BasicHttpContext()); - - if (response.getStatusLine().getStatusCode() != 200) { - - return null; - } - HttpEntity entity = response.getEntity(); - if (entity != null) { - String resultStr = EntityUtils.toString(entity, "utf-8"); - return resultStr; - } - } catch (IOException e) { - throw new OApiException(e); - } finally { - if (response != null) try { - response.close(); - } catch (IOException e) { - throw new OApiException(e); - } - } - - return null; - } - - - public static JsonObject httpPost(String url, Object data) throws OApiException { - HttpPost httpPost = new HttpPost(url); - CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); - RequestConfig requestConfig = RequestConfig.custom(). - setSocketTimeout(10000).setConnectTimeout(10000).build(); - httpPost.setConfig(requestConfig); - httpPost.addHeader("Content-Type", "application/json"); - try { - String dataStr=JsonUtil.getJsonString(data); - StringEntity requestEntity = new StringEntity(dataStr, "utf-8"); - httpPost.setEntity(requestEntity); - response = httpClient.execute(httpPost, new BasicHttpContext()); - - if (response.getStatusLine().getStatusCode() != 200) { - - return null; - } - - HttpEntity entity = response.getEntity(); - - if (entity != null) { - String resultStr = EntityUtils.toString(entity, "utf-8"); - return jsonObject.getAsJsonObject(resultStr); - } - } catch (IOException e) { - throw new OApiException(e); - } finally { - if (response != null) try { - response.close(); - } catch (IOException e) { - throw new OApiException(e); - } - } - - return null; - } - - - - /** - * Get方法 - * - * @param url:地址 - * @param returnClassName:返回对象类型,如:String.class - * @param parameters:parameter参数 - * @return - */ - public static T getByRest(String url, Class returnClassName, Map parameters){ - if (parameters == null) { - return restTemplate.getForObject(url, returnClassName); - } - return restTemplate.getForObject(url, returnClassName, parameters); - } - - /** - * post请求,包含了路径,返回类型,Header,Parameter - * - * @param url:地址 - * @param returnClassName:返回对象类型,如:String.class - * @param inputParameter - * @param jsonBody - * @return - */ - public static T postByRest(String url,Class returnClassName,Map inputParameter,String jsonBody){ - - org.springframework.http.HttpEntity formEntity = new org.springframework.http.HttpEntity<>(jsonBody); - if (inputParameter==null) { - return restTemplate.postForObject(url, formEntity, returnClassName); - } - return restTemplate.postForObject(url, formEntity, returnClassName, inputParameter); - } - - -/* - public static String postWithKey(String appid,String keyPath, String url, WxRefundDto dto) throws OApiException { - SSLContext sslContext = Pksc12KeyStore.initSSLContext(appid,dto.getMch_id(),keyPath); - HttpRequest request = HttpRequest.post(url).withConnectionProvider(new SSLSocketHttpConnectionProvider(sslContext)); - request.bodyText(dto.toXml()); - HttpResponse response = request.send(); - return response.bodyText(); - }*/ - - - public static void main(String[] args) { - - /* String jsonStr="{\"component_appid\":\"wxa797588149020de4\",\"component_verify_ticket\":\"ticket@@@6PEMgS7QZ2xzxJn9bdrOd6DB2xzm5I3liChyE8l4MdkruB10OzJl0FNsirqBXWoiB631xmw2fCHf84wCOSt9ZA\",\"component_appsecret\":\"a38dd974a9e6490dfbf5b21cd38f9996\"}\n"; - String json= HttpHelper.postByRest(Api.component_token,String.class,null,jsonStr); - Map jsonMap= JsonUtil.json2Obj(json,Map.class); - - - - - System.out.println(jsonMap);*/ - - - try { - JsonObject jo= HttpHelper.httpPost("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=7_LptTbnbGrlk8OrF3fSreUPozwvDXm_lE1LB-lqVXxD5VYW2XLcRCQ3G4FTwhe1LR670PkaItKHZm7TY4Ms-ECf8oDslqhyE3rUMo3GrqKLOFs8owbj9SSkF3Y6kYqd0GiYtzbgNLopPeP8AiDNYdABAXHS",null); - System.out.println(jo.toString()); - } catch (Exception e) { - e.printStackTrace(); - } - } - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/IDGenerate.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/IDGenerate.java deleted file mode 100644 index a8d3c4e..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/IDGenerate.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.github.xiaour.utils; - -import java.util.Date; -import java.util.Random; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @Author: Xiaour - * @Description: 一个基于Twitter的 - * @Date: 2018/8/22 14:24 - */ -public class IDGenerate { - - private static final long startTimeStamp = 1534919378079L; //定义一个起始时间 new Date().getTime() - - private static final long workerIdBits = 6L; - private static final long dataCenterIdBits = 6L; - private static final long maxWorkerId = -1L ^ (-1L << workerIdBits); - private static final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits); - - private static final long sequenceBits = 14L; - private static final long workerIdShift = sequenceBits; - private static final long dataCenterIdShift = sequenceBits + workerIdBits; - private static final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits; - private static final long sequenceMask = -1L ^ (-1L << sequenceBits); - private static final Random r = new Random(); - - private final long workerId; - private final long dataCenterId; - private final long idEpoch; - private long lastTimestamp = -1L; - private long sequence = 0; - - public IDGenerate() { - this(startTimeStamp); - } - - public IDGenerate(long idEpoch) { - this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDataCenterId), 0, idEpoch); - } - - public IDGenerate(long workerId, long dataCenterId, long sequence) { - this(workerId, dataCenterId, sequence, startTimeStamp); - } - - public IDGenerate(long workerId, long dataCenterId, long sequence, long idEpoch) { - this.workerId = workerId; - this.dataCenterId = dataCenterId; - this.sequence = sequence; - this.idEpoch = idEpoch; - - if (workerId < 0 || workerId > maxWorkerId) { - throw new IllegalArgumentException("workerId is illegal: " + workerId); - } - if (dataCenterId < 0 || dataCenterId > maxDataCenterId) { - throw new IllegalArgumentException("dataCenterId is illegal: " + dataCenterId); - } - - if (idEpoch >= timeGen()) { - throw new IllegalArgumentException("idEpoch is illegal: " + idEpoch); - } - } - - public long getDataCenterId() { - return dataCenterId; - } - - public long getWorkerId() { - return workerId; - } - - public long getTime() { - return timeGen(); - } - - public synchronized long nextId() { - long timestamp = timeGen(); - if (timestamp < lastTimestamp) { - throw new IllegalArgumentException("Clock moved backwards."); - } - - if (lastTimestamp == timestamp) { - sequence = (sequence + 1) & sequenceMask; - if (sequence == 0) { - timestamp = tilNextMillis(lastTimestamp); - } - } else { - sequence = 0; - } - - lastTimestamp = timestamp; - long id = ((timestamp - idEpoch) << timestampLeftShift) | (dataCenterId << - dataCenterIdShift) | (workerId << workerIdShift) | sequence; - return id; - } - - public long getIdTimestamp(long id) { - return idEpoch + (id >> timestampLeftShift); - } - - private long tilNextMillis(long lastTimestamp) { - long timestamp = timeGen(); - while (timestamp <= lastTimestamp) { - timestamp = timeGen(); - } - - return timestamp; - } - - private long timeGen() { - return System.currentTimeMillis(); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("IdBitWorker{"); - sb.append("workerId=").append(workerId); - sb.append(", dataCenterId=").append(dataCenterId); - sb.append(", idEpoch=").append(idEpoch); - sb.append(", lastTimestamp=").append(lastTimestamp); - sb.append(", sequence=").append(sequence); - sb.append('}'); - return sb.toString(); - } - - public static void main(String[] args) throws Exception { - IDGenerate worker = new IDGenerate(); - ExecutorService executor = Executors.newFixedThreadPool(8); - - CountDownLatch countDownLatch = new CountDownLatch(1000000); - Runnable run = () -> { - //这里是最主要ID部分 - System.out.println(worker.nextId()); - countDownLatch.countDown(); - }; - - long startTime = System.currentTimeMillis(); - for (int i = 0; i < 1000000; i++) { - executor.execute(run); - } - countDownLatch.await(); - System.out.println(System.currentTimeMillis() - startTime); - executor.shutdown(); - - System.out.println(new Date().getTime()); - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/JsonUtil.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/JsonUtil.java deleted file mode 100644 index 9b18bb9..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/JsonUtil.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.github.xiaour.utils; - -import com.google.gson.*; -import com.google.gson.reflect.TypeToken; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class JsonUtil{ - - - private static Gson gson = null; - - static{ - gson = new Gson(); - } - - public static synchronized Gson newInstance(){ - if(gson == null){ - gson = new Gson(); - } - return gson; - } - - public static String getJsonString(Object obj){ - return gson.toJson(obj); - } - - public static T toBean(String json,Class clz){ - - return gson.fromJson(json, clz); - } - - public static Map readJson2MapObj(String json,Class clz){ - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map result = new HashMap<>(); - for(String key:map.keySet()){ - result.put(key,gson.fromJson(map.get(key),clz) ); - } - return result; - } - - public static T json2Obj(String json,Class clz){ - return gson.fromJson(json,clz); - } - - public static Map toMap(String json){ - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - return map; - } - - public static Map readJsonStrMap(String json) { - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map result = new HashMap<>(); - for(String key:map.keySet()){ - result.put(key,gson.fromJson(map.get(key),String.class) ); - } - return result; - } - - public static Map readJsonByteMap(String json) { - Map map = gson.fromJson(json, new TypeToken>(){}.getType()); - Map vmap = new HashMap<>(); - for(String key:map.keySet()){ - vmap.put(key.getBytes(),gson.fromJson(map.get(key),String.class).getBytes() ); - } - return vmap; - - } - - - public static List readJson2Array(String json, Class clz){ - JsonArray array = new JsonParser().parse(json).getAsJsonArray(); - List list = new ArrayList<>(); - for(final JsonElement elem : array){ - list.add(gson.fromJson(elem, (Type)clz)); - } - return list; - } - -} \ No newline at end of file diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/PKCS7Encoder.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/PKCS7Encoder.java deleted file mode 100755 index 15d1cbb..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/PKCS7Encoder.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - */ - -// ------------------------------------------------------------------------ - -package com.github.xiaour.utils; - -import java.nio.charset.Charset; -import java.util.Arrays; - -/** - * 提供基于PKCS7算法的加解密接口. - */ -class PKCS7Encoder { - static Charset CHARSET = Charset.forName("utf-8"); - static int BLOCK_SIZE = 32; - - /** - * 获得对明文进行补位填充的字节. - * - * @param count 需要进行填充补位操作的明文字节个数 - * @return 补齐用的字节数组 - */ - static byte[] encode(int count) { - // 计算需要填充的位数 - int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); - if (amountToPad == 0) { - amountToPad = BLOCK_SIZE; - } - // 获得补位所用的字符 - char padChr = chr(amountToPad); - String tmp = new String(); - for (int index = 0; index < amountToPad; index++) { - tmp += padChr; - } - return tmp.getBytes(CHARSET); - } - - /** - * 删除解密后明文的补位字符 - * - * @param decrypted 解密后的明文 - * @return 删除补位字符后的明文 - */ - static byte[] decode(byte[] decrypted) { - int pad = (int) decrypted[decrypted.length - 1]; - if (pad < 1 || pad > 32) { - pad = 0; - } - return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); - } - - /** - * 将数字转化成ASCII码对应的字符,用于对明文进行补码 - * - * @param a 需要转化的数字 - * @return 转化得到的字符 - */ - static char chr(int a) { - byte target = (byte) (a & 0xFF); - return (char) target; - } - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/SHA1.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/SHA1.java deleted file mode 100755 index 0d257f0..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/SHA1.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - */ - -// ------------------------------------------------------------------------ - -package com.github.xiaour.utils; - -import com.github.xiaour.exception.AesException; - -import java.security.MessageDigest; -import java.util.Arrays; - -/** - * SHA1 class - * - * 计算公众平台的消息签名接口. - */ -class SHA1 { - - /** - * 用SHA1算法生成安全签名 - * @param token 票据 - * @param timestamp 时间戳 - * @param nonce 随机字符串 - * @param encrypt 密文 - * @return 安全签名 - * @throws AesException - */ - public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException - { - try { - String[] array = new String[] { token, timestamp, nonce, encrypt }; - StringBuffer sb = new StringBuffer(); - // 字符串排序 - Arrays.sort(array); - for (int i = 0; i < 4; i++) { - sb.append(array[i]); - } - String str = sb.toString(); - // SHA1签名生成 - MessageDigest md = MessageDigest.getInstance("SHA-1"); - md.update(str.getBytes()); - byte[] digest = md.digest(); - - StringBuffer hexstr = new StringBuffer(); - String shaHex = ""; - for (int i = 0; i < digest.length; i++) { - shaHex = Integer.toHexString(digest[i] & 0xFF); - if (shaHex.length() < 2) { - hexstr.append(0); - } - hexstr.append(shaHex); - } - return hexstr.toString(); - } catch (Exception e) { - e.printStackTrace(); - throw new AesException(AesException.ComputeSignatureError); - } - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Test.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Test.java deleted file mode 100644 index 3196893..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Test.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.github.xiaour.utils; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/3/2 上午10:35 - */ -public class Test { - - -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCrypt.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCrypt.java deleted file mode 100755 index 6019a47..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCrypt.java +++ /dev/null @@ -1,289 +0,0 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - */ - -// ------------------------------------------------------------------------ - -/** - * 针对org.apache.commons.codec.binary.Base64, - * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) - * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi - */ -package com.github.xiaour.utils; - -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Random; - -import javax.crypto.Cipher; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import com.github.xiaour.exception.AesException; -import org.apache.commons.codec.binary.Base64; - -/** - * 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串). - *
    - *
  1. 第三方回复加密消息给公众平台
  2. - *
  3. 第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。
  4. - *
- * 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案 - *
    - *
  1. 在官方网站下载JCE无限制权限策略文件(JDK7的下载地址: - * http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
  2. - *
  3. 下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt
  4. - *
  5. 如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件
  6. - *
  7. 如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件
  8. - *
- */ -public class WXBizMsgCrypt { - static Charset CHARSET = Charset.forName("utf-8"); - Base64 base64 = new Base64(); - byte[] aesKey; - String token; - String appId; - - /** - * 构造函数 - * @param token 公众平台上,开发者设置的token - * @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey - * @param appId 公众平台appid - * - * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 - */ - public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException { - if (encodingAesKey.length() != 43) { - throw new AesException(AesException.IllegalAesKey); - } - - this.token = token; - this.appId = appId; - aesKey = Base64.decodeBase64(encodingAesKey + "="); - } - - // 生成4个字节的网络字节序 - byte[] getNetworkBytesOrder(int sourceNumber) { - byte[] orderBytes = new byte[4]; - orderBytes[3] = (byte) (sourceNumber & 0xFF); - orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF); - orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF); - orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF); - return orderBytes; - } - - // 还原4个字节的网络字节序 - int recoverNetworkBytesOrder(byte[] orderBytes) { - int sourceNumber = 0; - for (int i = 0; i < 4; i++) { - sourceNumber <<= 8; - sourceNumber |= orderBytes[i] & 0xff; - } - return sourceNumber; - } - - // 随机生成16位字符串 - public String getRandomStr() { - String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - Random random = new Random(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < 16; i++) { - int number = random.nextInt(base.length()); - sb.append(base.charAt(number)); - } - return sb.toString(); - } - - /** - * 对明文进行加密. - * - * @param text 需要加密的明文 - * @return 加密后base64编码的字符串 - * @throws AesException aes加密失败 - */ - public String encrypt(String randomStr, String text) throws AesException { - ByteGroup byteCollector = new ByteGroup(); - byte[] randomStrBytes = randomStr.getBytes(CHARSET); - byte[] textBytes = text.getBytes(CHARSET); - byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); - byte[] appidBytes = appId.getBytes(CHARSET); - - // randomStr + networkBytesOrder + text + appid - byteCollector.addBytes(randomStrBytes); - byteCollector.addBytes(networkBytesOrder); - byteCollector.addBytes(textBytes); - byteCollector.addBytes(appidBytes); - - // ... + pad: 使用自定义的填充方式对明文进行补位填充 - byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); - byteCollector.addBytes(padBytes); - - // 获得最终的字节流, 未加密 - byte[] unencrypted = byteCollector.toBytes(); - - try { - // 设置加密模式为AES的CBC模式 - Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); - IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); - cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); - - // 加密 - byte[] encrypted = cipher.doFinal(unencrypted); - - // 使用BASE64对加密后的字符串进行编码 - String base64Encrypted = base64.encodeToString(encrypted); - - return base64Encrypted; - } catch (Exception e) { - e.printStackTrace(); - throw new AesException(AesException.EncryptAESError); - } - } - - /** - * 对密文进行解密. - * - * @param text 需要解密的密文 - * @return 解密得到的明文 - * @throws AesException aes解密失败 - */ - public String decrypt(String text) throws AesException { - byte[] original; - try { - // 设置解密模式为AES的CBC模式 - Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); - SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); - IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); - cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); - - // 使用BASE64对密文进行解码 - byte[] encrypted = Base64.decodeBase64(text); - - // 解密 - original = cipher.doFinal(encrypted); - } catch (Exception e) { - e.printStackTrace(); - throw new AesException(AesException.DecryptAESError); - } - - String xmlContent, from_appid; - try { - // 去除补位字符 - byte[] bytes = PKCS7Encoder.decode(original); - - // 分离16位随机字符串,网络字节序和AppId - byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); - - int xmlLength = recoverNetworkBytesOrder(networkOrder); - - xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET); - from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), - CHARSET); - } catch (Exception e) { - e.printStackTrace(); - throw new AesException(AesException.IllegalBuffer); - } - - // appid不相同的情况 - if (!from_appid.equals(appId)) { - throw new AesException(AesException.ValidateAppidError); - } - return xmlContent; - - } - - /** - * 将公众平台回复用户的消息加密打包. - *
    - *
  1. 对要发送的消息进行AES-CBC加密
  2. - *
  3. 生成安全签名
  4. - *
  5. 将消息密文和安全签名打包成xml格式
  6. - *
- * - * @param replyMsg 公众平台待回复用户的消息,xml格式的字符串 - * @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp - * @param nonce 随机串,可以自己生成,也可以用URL参数的nonce - * - * @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 - * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 - */ - public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException { - // 加密 - String encrypt = encrypt(getRandomStr(), replyMsg); - - // 生成安全签名 - if (timeStamp == "") { - timeStamp = Long.toString(System.currentTimeMillis()); - } - - String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt); - - // System.out.println("发送给平台的签名是: " + signature[1].toString()); - // 生成发送的xml - String result = XMLParse.generate(encrypt, signature, timeStamp, nonce); - return result; - } - - /** - * 检验消息的真实性,并且获取解密后的明文. - *
    - *
  1. 利用收到的密文生成安全签名,进行签名验证
  2. - *
  3. 若验证通过,则提取xml中的加密消息
  4. - *
  5. 对消息进行解密
  6. - *
- * - * @param msgSignature 签名串,对应URL参数的msg_signature - * @param timeStamp 时间戳,对应URL参数的timestamp - * @param nonce 随机串,对应URL参数的nonce - * @param encrypt 密文,对应POST请求的数据 - * - * @return 解密后的原文 - * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 - */ - public String decryptMsg(String msgSignature, String timeStamp, String nonce, String encrypt) - throws AesException { - - // 密钥,公众账号的app secret - // 提取密文 - - // 验证安全签名 - String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt); - - // 和URL中的签名比较是否相等 - // System.out.println("第三方收到URL中的签名:" + msg_sign); - // System.out.println("第三方校验签名:" + signature); - if (!signature.equals(msgSignature)) { - throw new AesException(AesException.ValidateSignatureError); - } - - // 解密 - String result = decrypt(encrypt); - return result; - } - - /** - * 验证URL - * @param msgSignature 签名串,对应URL参数的msg_signature - * @param timeStamp 时间戳,对应URL参数的timestamp - * @param nonce 随机串,对应URL参数的nonce - * @param echoStr 随机串,对应URL参数的echostr - * - * @return 解密之后的echostr - * @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 - */ - public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr) - throws AesException { - String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr); - - if (!signature.equals(msgSignature)) { - throw new AesException(AesException.ValidateSignatureError); - } - - String result = decrypt(echoStr); - return result; - } - -} \ No newline at end of file diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCryptTest.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCryptTest.java deleted file mode 100755 index fb28989..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/WXBizMsgCryptTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.github.xiaour.utils; - -import static org.junit.Assert.*; - -import java.io.IOException; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import com.github.xiaour.exception.AesException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -public class WXBizMsgCryptTest { - String encodingAesKey = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; - String token = "pamtest"; - String timestamp = "1409304348"; - String nonce = "xxxxxx"; - String appId = "wxb11529c136998cb6"; - String replyMsg = "我是中文abcd123"; - String xmlFormat = ""; - String afterAesEncrypt = "jn1L23DB+6ELqJ+6bruv21Y6MD7KeIfP82D6gU39rmkgczbWwt5+3bnyg5K55bgVtVzd832WzZGMhkP72vVOfg=="; - String randomStr = "aaaabbbbccccdddd"; - - String replyMsg2 = "1407743423"; - String afterAesEncrypt2 = "jn1L23DB+6ELqJ+6bruv23M2GmYfkv0xBh2h+XTBOKVKcgDFHle6gqcZ1cZrk3e1qjPQ1F4RsLWzQRG9udbKWesxlkupqcEcW7ZQweImX9+wLMa0GaUzpkycA8+IamDBxn5loLgZpnS7fVAbExOkK5DYHBmv5tptA9tklE/fTIILHR8HLXa5nQvFb3tYPKAlHF3rtTeayNf0QuM+UW/wM9enGIDIJHF7CLHiDNAYxr+r+OrJCmPQyTy8cVWlu9iSvOHPT/77bZqJucQHQ04sq7KZI27OcqpQNSto2OdHCoTccjggX5Z9Mma0nMJBU+jLKJ38YB1fBIz+vBzsYjrTmFQ44YfeEuZ+xRTQwr92vhA9OxchWVINGC50qE/6lmkwWTwGX9wtQpsJKhP+oS7rvTY8+VdzETdfakjkwQ5/Xka042OlUb1/slTwo4RscuQ+RdxSGvDahxAJ6+EAjLt9d8igHngxIbf6YyqqROxuxqIeIch3CssH/LqRs+iAcILvApYZckqmA7FNERspKA5f8GoJ9sv8xmGvZ9Yrf57cExWtnX8aCMMaBropU/1k+hKP5LVdzbWCG0hGwx/dQudYR/eXp3P0XxjlFiy+9DMlaFExWUZQDajPkdPrEeOwofJb"; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNormal() throws ParserConfigurationException, SAXException, IOException { - try { - WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); - String afterEncrpt = pc.encryptMsg(replyMsg, timestamp, nonce); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - StringReader sr = new StringReader(afterEncrpt); - InputSource is = new InputSource(sr); - Document document = db.parse(is); - - Element root = document.getDocumentElement(); - NodeList nodelist1 = root.getElementsByTagName("Encrypt"); - NodeList nodelist2 = root.getElementsByTagName("MsgSignature"); - - String encrypt = nodelist1.item(0).getTextContent(); - String msgSignature = nodelist2.item(0).getTextContent(); - String fromXML = String.format(xmlFormat, encrypt); - - // 第三方收到公众号平台发送的消息 - String afterDecrpt = pc.decryptMsg(msgSignature, timestamp, nonce, fromXML); - assertEquals(replyMsg, afterDecrpt); - } catch (AesException e) { - fail("正常流程,怎么就抛出异常了??????"); - } - } - - @Test - public void testAesEncrypt() { - try { - WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); - assertEquals(afterAesEncrypt, pc.encrypt(randomStr, replyMsg)); - } catch (AesException e) { - e.printStackTrace(); - fail("no异常"); - } - } - - @Test - public void testAesEncrypt2() { - try { - WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); - assertEquals(afterAesEncrypt2, pc.encrypt(randomStr, replyMsg2)); - - } catch (AesException e) { - e.printStackTrace(); - fail("no异常"); - } - } - - @Test - public void testIllegalAesKey() { - try { - new WXBizMsgCrypt(token, "abcde", appId); - } catch (AesException e) { - assertEquals(AesException.IllegalAesKey, e.getCode()); - return; - } - fail("错误流程不抛出异常???"); - } - - @Test - public void testValidateSignatureError() throws ParserConfigurationException, SAXException, - IOException { - try { - WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId); - String afterEncrpt = pc.encryptMsg(replyMsg, timestamp, nonce); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - StringReader sr = new StringReader(afterEncrpt); - InputSource is = new InputSource(sr); - Document document = db.parse(is); - - Element root = document.getDocumentElement(); - NodeList nodelist1 = root.getElementsByTagName("Encrypt"); - - String encrypt = nodelist1.item(0).getTextContent(); - String fromXML = String.format(xmlFormat, encrypt); - pc.decryptMsg("12345", timestamp, nonce, fromXML); // 这里签名错误 - } catch (AesException e) { - assertEquals(AesException.ValidateSignatureError, e.getCode()); - return; - } - fail("错误流程不抛出异常???"); - } - - @Test - public void testVerifyUrl() throws AesException { - WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("QDG6eK", - "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C", "wx5823bf96d3bd56c7"); - String verifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3"; - String timeStamp = "1409659589"; - String nonce = "263014780"; - String echoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ=="; - wxcpt.verifyUrl(verifyMsgSig, timeStamp, nonce, echoStr); - // 只要不抛出异常就好 - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/XMLParse.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/XMLParse.java deleted file mode 100755 index 67d860f..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/XMLParse.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 对公众平台发送给公众账号的消息加解密示例代码. - * - * @copyright Copyright (c) 1998-2014 Tencent Inc. - */ - -// ------------------------------------------------------------------------ - -package com.github.xiaour.utils; - -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import com.github.xiaour.exception.AesException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; - -/** - * XMLParse class - * - * 提供提取消息格式中的密文及生成回复消息格式的接口. - */ -class XMLParse { - - /** - * 提取出xml数据包中的加密消息 - * @param xmltext 待提取的xml字符串 - * @return 提取出的加密消息字符串 - * @throws AesException - */ - public static Object[] extract(String xmltext) throws AesException { - Object[] result = new Object[3]; - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - StringReader sr = new StringReader(xmltext); - InputSource is = new InputSource(sr); - Document document = db.parse(is); - - Element root = document.getDocumentElement(); - NodeList nodelist1 = root.getElementsByTagName("Encrypt"); - - result[0] = 0; - result[1] = nodelist1.item(0).getTextContent(); - - if(root.getElementsByTagName("ToUserName")!=null) { - NodeList nodelist2 = root.getElementsByTagName("ToUserName"); - result[2] = nodelist2.item(0).getTextContent(); - } - return result; - } catch (Exception e) { - e.printStackTrace(); - throw new AesException(AesException.ParseXmlError); - } - } - - /** - * 生成xml消息 - * @param encrypt 加密后的消息密文 - * @param signature 安全签名 - * @param timestamp 时间戳 - * @param nonce 随机字符串 - * @return 生成的xml字符串 - */ - public static String generate(String encrypt, String signature, String timestamp, String nonce) { - - String format = "\n" + "\n" - + "\n" - + "%3$s\n" + "\n" + ""; - return String.format(format, encrypt, signature, timestamp, nonce); - - } -} diff --git a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Xml2JsonUtil.java b/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Xml2JsonUtil.java deleted file mode 100644 index b9b5c4f..0000000 --- a/SpringBootDemoV2/src/main/java/com/github/xiaour/utils/Xml2JsonUtil.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.github.xiaour.utils; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import org.dom4j.*; - -import java.util.List; - -/** - * XML转成JSON - * - * @ClassName Xml2JsonUtil - * @author xiaour@github.com - * @Date 2017年6月13日 下午6:30:00 - * @version V2.0.0 - */ -public class Xml2JsonUtil { - - /** - * xml转json - * @param xmlStr - * @return - * @throws DocumentException - */ - public static JsonObject xml2Json(String xmlStr) throws DocumentException{ - Document doc= DocumentHelper.parseText(xmlStr); - JsonObject json=new JsonObject(); - dom4j2Json(doc.getRootElement(), json); - return json; - } - - /** - * xml转json - * @param element - * @param json - */ - private static void dom4j2Json(Element element,JsonObject json){ - //如果是属性 - for(Object o:element.attributes()){ - Attribute attr=(Attribute)o; - if(!isEmpty(attr.getValue())){ - json.addProperty("@"+attr.getName(), attr.getValue()); - } - } - List chdEl=element.elements(); - if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值 - json.addProperty(element.getName(), element.getText()); - } - - for(Element e:chdEl){//有子元素 - if(!e.elements().isEmpty()){//子元素也有子元素 - JsonObject chdjson=new JsonObject(); - dom4j2Json(e,chdjson); - Object o=json.get(e.getName()); - if(o!=null){ - JsonArray jsona=null; - if(o instanceof JsonObject){//如果此元素已存在,则转为jsonArray - JsonObject jsono=(JsonObject)o; - json.remove(e.getName()); - jsona=new JsonArray(); - jsona.add(jsono); - jsona.add(chdjson); - } - if(o instanceof JsonArray){ - jsona=(JsonArray)o; - jsona.add(chdjson); - } - json.add(e.getName(), jsona); - }else{ - if(!chdjson.isJsonNull()){ - json.add(e.getName(), chdjson); - } - } - - - }else{//子元素没有子元素 - for(Object o:element.attributes()){ - Attribute attr=(Attribute)o; - if(!isEmpty(attr.getValue())){ - json.addProperty("@"+attr.getName(), attr.getValue()); - } - } - if(!e.getText().isEmpty()){ - json.addProperty(e.getName(), e.getText()); - } - } - } - } - - private static boolean isEmpty(String str) { - - if (str == null || str.trim().isEmpty() || "null".equals(str)) { - return true; - } - return false; - } - -} diff --git a/SpringBootDemoV2/src/main/resources/application.yml b/SpringBootDemoV2/src/main/resources/application.yml deleted file mode 100644 index c1dbf67..0000000 --- a/SpringBootDemoV2/src/main/resources/application.yml +++ /dev/null @@ -1,25 +0,0 @@ -spring: - banner: - image: - location: static/banner.png -duck: - duckName: DonDonald Fauntleroy Duck - totalCount: 1 - -server: - servlet: - context-path: /xiaour-dubbo - port: 8081 -dubbo: - scan: - base-packages: com.github.xiaour.service - application: - id: xiaour-provider - name: xiaour-provider - registry: - address: zookeeper://127.0.0.1:2181 - id: my-registry - protocol: - id: dubbo - name: dubbo - port: 20880 \ No newline at end of file diff --git a/SpringBootDemoV2/src/main/resources/static/banner.png b/SpringBootDemoV2/src/main/resources/static/banner.png deleted file mode 100644 index 427c3eb..0000000 Binary files a/SpringBootDemoV2/src/main/resources/static/banner.png and /dev/null differ diff --git a/SpringBootDemoV2/src/test/java/com/github/xiaour/SpringBootDemoV2ApplicationTests.java b/SpringBootDemoV2/src/test/java/com/github/xiaour/SpringBootDemoV2ApplicationTests.java deleted file mode 100644 index a91a70c..0000000 --- a/SpringBootDemoV2/src/test/java/com/github/xiaour/SpringBootDemoV2ApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.github.xiaour; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootDemoV2ApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/SpringBootDemoV3/.gitignore b/SpringBootDemoV3/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/SpringBootDemoV3/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ - -### VS Code ### -.vscode/ diff --git a/SpringBootDemoV3/pom.xml b/SpringBootDemoV3/pom.xml deleted file mode 100644 index 110db5f..0000000 --- a/SpringBootDemoV3/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 3.2.3 - - - - com.github.xiaour - springbootv3 - 0.0.1-SNAPSHOT - SpringBootDemoV3 - Demo project for Spring Boot - jar - - - 17 - - - - - - org.springframework.boot - spring-boot-starter - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-web - - - - io.github.xiaour - easy-export - 1.0.1-RELEASE - - - - com.alibaba - easyexcel - 2.2.3 - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/SpringBootDemoV3Application.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/SpringBootDemoV3Application.java deleted file mode 100644 index 7b98f02..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/SpringBootDemoV3Application.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.xiaour.spring.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringBootDemoV3Application { - - public static void main(String[] args) { - SpringApplication.run(SpringBootDemoV3Application.class, args); - //System.out.println(Math.max(10,11)); - } - - -} diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/controller/CatController.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/controller/CatController.java deleted file mode 100644 index d740815..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/controller/CatController.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaour.spring.boot.controller; - -import com.xiaour.spring.boot.entity.PageIndex; -import com.xiaour.spring.boot.entity.PageInfo; -import com.xiaour.spring.boot.service.CatService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/cat") -public class CatController { - - private CatService catService; - - @Autowired - public CatController(CatService catService) { - this.catService = catService; - } - - @GetMapping("list") - public PageInfo getCatList() { - PageIndex index = new PageIndex(); - index.setPageIndex(1); - index.setPageSize(30); - return catService.getCatList(index); - } - - - - - -} diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/Cat.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/Cat.java deleted file mode 100644 index 5aef16e..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/Cat.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.xiaour.spring.boot.entity; - -import com.alibaba.excel.annotation.ExcelProperty; - -public class Cat { - - /** - * 宠物昵称 - */ - @ExcelProperty(value = "昵称") - private String nickName; - - /** - * 年龄 - */ - @ExcelProperty(value = "年龄") - private Integer age; - - /** - * 品种 - */ - @ExcelProperty(value = "品种") - private String category; - - public Cat() { - } - - public Cat(String nickName, Integer age, String category) { - this.nickName = nickName; - this.age = age; - this.category = category; - } - - public String getNickName() { - return nickName; - } - - public Cat setNickName(String nickName) { - this.nickName = nickName; - return this; - } - - public Integer getAge() { - return age; - } - - public Cat setAge(Integer age) { - this.age = age; - return this; - } - - public String getCategory() { - return category; - } - - public Cat setCategory(String category) { - this.category = category; - return this; - } -} diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageIndex.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageIndex.java deleted file mode 100644 index abaf3dc..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageIndex.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaour.spring.boot.entity; - -public class PageIndex { - - private Integer pageIndex; - - private Integer pageSize; - - public Integer getPageIndex() { - return pageIndex; - } - - public void setPageIndex(Integer pageIndex) { - this.pageIndex = pageIndex; - } - - public Integer getPageSize() { - return pageSize; - } - - public void setPageSize(Integer pageSize) { - this.pageSize = pageSize; - } -} diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageInfo.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageInfo.java deleted file mode 100644 index 53fafdd..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/entity/PageInfo.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.xiaour.spring.boot.entity; - -import java.util.List; - -public class PageInfo { - - private List list; - - private Integer total; - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Integer getTotal() { - return total; - } - - public void setTotal(Integer total) { - this.total = total; - } -} diff --git a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/service/CatService.java b/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/service/CatService.java deleted file mode 100644 index ba1b8c1..0000000 --- a/SpringBootDemoV3/src/main/java/com/xiaour/spring/boot/service/CatService.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.xiaour.spring.boot.service; - -import com.github.xiaour.easyexport.annotation.EasyExport; -import com.github.xiaour.easyexport.annotation.EasyExportSingle; -import com.xiaour.spring.boot.entity.Cat; -import com.xiaour.spring.boot.entity.PageIndex; -import com.xiaour.spring.boot.entity.PageInfo; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; - -@EasyExport -@Service -public class CatService { - - /** - * 这里主要是模拟数据和分页参数的一些主要逻辑 - * @param pageIndex 模拟的分页参数,这里面是伪代码,无需实现 - * @return - */ - @EasyExportSingle(value = "小猫明细",modelClass = Cat.class) - public PageInfo getCatList(PageIndex pageIndex){ - - PageInfo page = new PageInfo(); - - List list = new ArrayList<>(); - - //下面提供了两种实体赋值方式,大家可以试试那种更方便 - Cat cat1 = new Cat("咪咪",1,"波斯猫"); - - Cat cat2 = new Cat().setNickName("汤姆").setAge(6).setCategory("金渐层"); - - list.add(cat1); - - list.add(cat2); - - page.setList(list); - - page.setTotal(list.size()); - - return page; - } -} diff --git a/SpringBootDemoV3/src/main/resources/application.properties b/SpringBootDemoV3/src/main/resources/application.properties deleted file mode 100644 index a39567d..0000000 --- a/SpringBootDemoV3/src/main/resources/application.properties +++ /dev/null @@ -1,15 +0,0 @@ -server.servlet.context-path= /demo3 - -#??easyexport -easyexport.enabled=true -#?????? -#?????????? -easyexport.fetch.page.size=5000 -#???????????????????true??????? -easyexport.file.delete=true -#???????????????????Sheet????sheet???150000 -easyexport.file.sheet.size=15000 -#???? -easyexport.field.page.number=pageIndex -#??????? -easyexport.field.page.size=pageSize \ No newline at end of file diff --git a/SpringBootDemoV3/src/test/java/com/xiaour/spring/boot/SpringBootDemoV3ApplicationTests.java b/SpringBootDemoV3/src/test/java/com/xiaour/spring/boot/SpringBootDemoV3ApplicationTests.java deleted file mode 100644 index bbe9d67..0000000 --- a/SpringBootDemoV3/src/test/java/com/xiaour/spring/boot/SpringBootDemoV3ApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.xiaour.spring.boot; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class SpringBootDemoV3ApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/SpringBootKafkaDemo/SpringBootKafkaDemo.iml b/SpringBootKafkaDemo/SpringBootKafkaDemo.iml deleted file mode 100644 index 7e471dc..0000000 --- a/SpringBootKafkaDemo/SpringBootKafkaDemo.iml +++ /dev/null @@ -1,92 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/SpringBootKafkaDemo/pom.xml b/SpringBootKafkaDemo/pom.xml deleted file mode 100644 index b0eb7a0..0000000 --- a/SpringBootKafkaDemo/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - - com.github.xiaour - KafkaDemo - 0.0.1-SNAPSHOT - jar - - kafka - Kafka Demo project for Spring Boot - - - org.springframework.boot - spring-boot-starter-parent - 2.0.2.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.kafka - spring-kafka - - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.code.gson - gson - 2.8.9 - - - org.springframework.boot - spring-boot-starter-web - 2.5.12 - - - org.springframework - spring-context - 5.2.22.RELEASE - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/KafkaApplication.java b/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/KafkaApplication.java deleted file mode 100644 index d7b1149..0000000 --- a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/KafkaApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaour.spring.boot.kafka; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class KafkaApplication { - - public static void main(String[] args) { - SpringApplication.run(KafkaApplication.class, args); - } -} diff --git a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/consumer/Consumer.java b/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/consumer/Consumer.java deleted file mode 100644 index 95a11f9..0000000 --- a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/consumer/Consumer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.xiaour.spring.boot.kafka.consumer; - -import org.apache.kafka.clients.consumer.ConsumerRecord; -import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.stereotype.Component; - -import java.util.Optional; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/5/22 15:03 - */ -@Component -public class Consumer { - - @KafkaListener(topics = {"test"}) - public void listen(ConsumerRecord record){ - - Optional kafkaMessage = Optional.ofNullable(record.value()); - - if (kafkaMessage.isPresent()) { - - Object message = kafkaMessage.get(); - System.out.println("---->"+record); - System.out.println("---->"+message); - - } - - } -} diff --git a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Message.java b/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Message.java deleted file mode 100644 index dd5c544..0000000 --- a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Message.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.xiaour.spring.boot.kafka.producer; - -import java.util.Date; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/5/22 15:09 - */ -public class Message { - - private String id; - - private String msg; - - private Date sendTime; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public Date getSendTime() { - return sendTime; - } - - public void setSendTime(Date sendTime) { - this.sendTime = sendTime; - } -} diff --git a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Producer.java b/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Producer.java deleted file mode 100644 index 772ed9c..0000000 --- a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/Producer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.xiaour.spring.boot.kafka.producer; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.stereotype.Component; - -import java.util.Date; -import java.util.UUID; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/5/22 15:07 - */ -@Component -public class Producer { - - @Autowired - private KafkaTemplate kafkaTemplate; - - private static Gson gson = new GsonBuilder().create(); - - //发送消息方法 - public void send() { - Message message = new Message(); - message.setId("KFK_"+System.currentTimeMillis()); - message.setMsg(UUID.randomUUID().toString()); - message.setSendTime(new Date()); - kafkaTemplate.send("test", gson.toJson(message)); - } - -} diff --git a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/SendController.java b/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/SendController.java deleted file mode 100644 index 6c66e13..0000000 --- a/SpringBootKafkaDemo/src/main/java/com/xiaour/spring/boot/kafka/producer/SendController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.xiaour.spring.boot.kafka.producer; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @Author: Xiaour - * @Description: - * @Date: 2018/5/22 15:13 - */ -@RestController -@RequestMapping("/kafka") -public class SendController { - - @Autowired - private Producer producer; - - @RequestMapping(value = "/send") - public String send() { - producer.send(); - return "{\"code\":0}"; - } -} diff --git a/SpringBootKafkaDemo/src/main/resources/application.yml b/SpringBootKafkaDemo/src/main/resources/application.yml deleted file mode 100644 index 0b19627..0000000 --- a/SpringBootKafkaDemo/src/main/resources/application.yml +++ /dev/null @@ -1,33 +0,0 @@ -server: - servlet: - context-path: / - port: 8080 -spring: - kafka: - bootstrap-servers: 127.0.0.1:9092 - #生产者的配置,大部分我们可以使用默认的,这里列出几个比较重要的属性 - producer: - #每批次发送消息的数量 - batch-size: 16 - #设置大于0的值将使客户端重新发送任何数据,一旦这些数据发送失败。注意,这些重试与客户端接收到发送错误时的重试没有什么不同。允许重试将潜在的改变数据的顺序,如果这两个消息记录都是发送到同一个partition,则第一个消息失败第二个发送成功,则第二条消息会比第一条消息出现要早。 - retries: 0 - #producer可以用来缓存数据的内存大小。如果数据产生速度大于向broker发送的速度,producer会阻塞或者抛出异常,以“block.on.buffer.full”来表明。这项设置将和producer能够使用的总内存相关,但并不是一个硬性的限制,因为不是producer使用的所有内存都是用于缓存。一些额外的内存会用于压缩(如果引入压缩机制),同样还有一些用于维护请求。 - buffer-memory: 33554432 - #key序列化方式 - key-serializer: org.apache.kafka.common.serialization.StringSerializer - value-serializer: org.apache.kafka.common.serialization.StringSerializer - #消费者的配置 - consumer: - #Kafka中没有初始偏移或如果当前偏移在服务器上不再存在时,默认区最新 ,有三个选项 【latest, earliest, none】 - auto-offset-reset: latest - #是否开启自动提交 - enable-auto-commit: true - #自动提交的时间间隔 - auto-commit-interval: 100 - #key的解码方式 - key-deserializer: org.apache.kafka.common.serialization.StringDeserializer - #value的解码方式 - value-deserializer: org.apache.kafka.common.serialization.StringDeserializer - #在/usr/local/etc/kafka/consumer.properties中有配置 - group-id: test-consumer-group - diff --git a/SpringBootKafkaDemo/src/test/java/com/xiaour/spring/boot/kafka/KafkaApplicationTests.java b/SpringBootKafkaDemo/src/test/java/com/xiaour/spring/boot/kafka/KafkaApplicationTests.java deleted file mode 100644 index 924f1ba..0000000 --- a/SpringBootKafkaDemo/src/test/java/com/xiaour/spring/boot/kafka/KafkaApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaour.spring.boot.kafka; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class KafkaApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/SpringBootKafkaDemo/target/classes/com/xiaour/spring/boot/kafka/producer/Message.class b/SpringBootKafkaDemo/target/classes/com/xiaour/spring/boot/kafka/producer/Message.class deleted file mode 100644 index 9b6edd7..0000000 Binary files a/SpringBootKafkaDemo/target/classes/com/xiaour/spring/boot/kafka/producer/Message.class and /dev/null differ diff --git a/SpringBootRocketMqDemo/.gitignore b/SpringBootRocketMqDemo/.gitignore deleted file mode 100644 index 82eca33..0000000 --- a/SpringBootRocketMqDemo/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/build/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ \ No newline at end of file diff --git a/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.jar b/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 9cc84ea..0000000 Binary files a/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.properties b/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index b573bb5..0000000 --- a/SpringBootRocketMqDemo/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip diff --git a/SpringBootRocketMqDemo/SpringbootRocketMQ.md b/SpringBootRocketMqDemo/SpringbootRocketMQ.md deleted file mode 100644 index 18cafd7..0000000 --- a/SpringBootRocketMqDemo/SpringbootRocketMQ.md +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: Springboot集成ROcketMQ -categories: [Springboot],[MQ] -date: 2018-05-23 10:43:12 -tags: ---- - -post-cover"" - -有一段时间没有写东西了,最近工作和生活上发生了一些变化,总算是有点时间来歇一歇自己想要分享的,2018年转眼过去一多半了,想来自己今年好像也没有太多的积累。尽可能的让自己能够多做一些技术上的事情。 - -从开篇写Springboot系列的教程已经一年多了,Springboot也从1.x升级到了2.x,目前教程中的代码部分大多都是使用Springboot2.x了。 - -Springboot从开始到流行起来的到现在的风靡是很多开发越来越简单,经我调查发现大部分开发人员都已经开始在生产环境使用,除了一些老的项目或者难以改变技术架构的项目外,Springboot可以说是作为JAVA开发人员必不可少的伙伴了。 - -如今大多数的JAVA系组件都开发除了自己的boot版本,有一些做的比较优秀,也有一些做的不是那么好,本篇要介绍的RocketMQ在boot上做的就不算很好,有很多开发者自己封装了boot版本,官方可能会在未来出现更好版本的boot;但是没有boot版没关系,咱们自己几行配置也是完全可以做到快速使用RocketMQ了。 - -在这里我要提一下官方版本的RocketMQ4.3,因为本文就是基于RocketMQ4.3的,"RocketMQ4.3正式发布支持了分布式事务"。这一消息让很多开发者跃跃欲试,以前rocketMQ没有将分布式事务作为一个发行版的部分,基本都是开发者自己实现的事务部分。下面我们从最基础的安装RocketMQ开始,再介绍代码中如何实现基本的配置。 - -###下载安装RocketMQ - -``` -# wget http://mirrors.hust.edu.cn/apache/rocketmq/4.3.0/rocketmq-all-4.3.0-source-release.zip -# unzip rocketmq-all-4.3.0-source-release.zip -# mvn -Prelease-all -DskipTests clean install -U -# cd distribution/target/apache-rocketmq -``` - -###启动NameServer,启动后NameServer的端口是9876,请确保自己的9876端口未被占用 -``` -# nohup sh bin/mqnamesrv & -# tail -f ~/logs/rocketmqlogs/namesrv.log - The Name Server boot success... -``` - -### 启动Broker -``` -# nohup sh bin/mqbroker -n localhost:9876 & -# tail -f ~/logs/rocketmqlogs/broker.log - The broker[%s, 172.30.30.233:10911] boot success... -``` -启动成功了之后我们就可以创建新的Springboot项目了,如何创建项目这里我就不在介绍了,Eclipse和Idea的方式大同小异,目录结构基本都是一样的。 - -首先每次说到Springboot的项目都是要先讲讲这个boot的配置,按照惯例呢我先给配置,配置上都有每一行配置的注释,大家可以参考。 -### 代码示例pom.xml -``` - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - org.apache.rocketmq - rocketmq-client - 4.3.0 - - - - org.springframework.boot - spring-boot-starter-web - RELEASE - - -``` -###application.yml -``` -apache: - rocketmq: -#消费者的配置 - consumer: - pushConsumer: XiaourPushConsumer -#生产者的配置 - producer: - producerGroup: Xiaour -#Nameserver的地址,这里配置你MQ安装的机器上的IP就好,我这里在本机安装的 - namesrvAddr: 127.0.0.1:9876 - ``` - -###Producer 消息生产者 -```java -import org.apache.commons.lang3.time.StopWatch; -import org.apache.rocketmq.client.exception.MQBrokerException; -import org.apache.rocketmq.client.exception.MQClientException; -import org.apache.rocketmq.client.producer.DefaultMQProducer; -import org.apache.rocketmq.client.producer.SendResult; -import org.apache.rocketmq.common.message.Message; -import org.apache.rocketmq.remoting.common.RemotingHelper; -import org.apache.rocketmq.remoting.exception.RemotingException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import java.io.UnsupportedEncodingException; - -/** - * @Author: Xiaour - * @Description:生产者 - * @Date: 2018/8/9 14:52 - */ - -@Component -public class Producer { - - /** - * 生产者的组名 - */ - @Value("${apache.rocketmq.producer.producerGroup}") - private String producerGroup; - - private DefaultMQProducer producer; - /** - * NameServer 地址 - */ - @Value("${apache.rocketmq.namesrvAddr}") - private String namesrvAddr; - - @PostConstruct - public void defaultMQProducer() { - - //生产者的组名 - producer= new DefaultMQProducer(producerGroup); - //指定NameServer地址,多个地址以 ; 隔开 - producer.setNamesrvAddr(namesrvAddr); - producer.setVipChannelEnabled(false); - try { - producer.start(); - System.out.println("-------->:producer启动了"); - } catch (MQClientException e) { - e.printStackTrace(); - } - } - - public String send(String topic,String tags,String body) throws InterruptedException, RemotingException, MQClientException, MQBrokerException, UnsupportedEncodingException { - Message message = new Message(topic, tags, body.getBytes(RemotingHelper.DEFAULT_CHARSET)); - StopWatch stop = new StopWatch(); - stop.start(); - SendResult result = producer.send(message); - System.out.println("发送响应:MsgId:" + result.getMsgId() + ",发送状态:" + result.getSendStatus()); - stop.stop(); - return "{\"MsgId\":\""+result.getMsgId()+"\"}"; - } -} -``` -###Consumer 消息消费者 - -```java -import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; -import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; -import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; -import org.apache.rocketmq.common.consumer.ConsumeFromWhere; -import org.apache.rocketmq.common.message.Message; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.CommandLineRunner; - -import org.springframework.stereotype.Component; - -/** - * @Author: Xiaour - * @Description:消费者 - * @Date: 2018/8/9 14:51 - */ - -@Component -public class Consumer implements CommandLineRunner { - - /** - * 消费者 - */ - @Value("${apache.rocketmq.consumer.pushConsumer}") - private String pushConsumer; - - /** - * NameServer 地址 - */ - @Value("${apache.rocketmq.namesrvAddr}") - private String namesrvAddr; - - - /** - * 初始化RocketMq的监听信息,渠道信息 - */ - public void messageListener(){ - - DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("SpringBootRocketMqGroup"); - - consumer.setNamesrvAddr(namesrvAddr); - try { - - // 订阅PushTopic下Tag为push的消息,都订阅消息 - consumer.subscribe("PushTopic", "push"); - - // 程序第一次启动从消息队列头获取数据 - consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); - //可以修改每次消费消息的数量,默认设置是每次消费一条 - consumer.setConsumeMessageBatchMaxSize(1); - - //在此监听中消费信息,并返回消费的状态信息 - consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> { - - // 会把不同的消息分别放置到不同的队列中 - for(Message msg:msgs){ - - System.out.println("接收到了消息:"+new String(msg.getBody())); - } - return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; - }); - - consumer.start(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void run(String... args) throws Exception { - this.messageListener(); - } -} -``` -###测试接口用例 -这里我们用一个接口来测试我们的消息发送会不会被消费者接收。 - -```java -@RestController -public class TestController { - @Autowired - private Producer producer; - - @RequestMapping("/push") - public String pushMsg(String msg){ - try { - return producer.send("PushTopic","push",msg); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (RemotingException e) { - e.printStackTrace(); - } catch (MQClientException e) { - e.printStackTrace(); - } catch (MQBrokerException e) { - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return "ERROR"; - } -} -``` -在Springboot启动类启动后,在浏览器访问http://127.0.0.1:8080/push?hello,页面提示{"MsgId":"AC100AB660C618B4AAC2XXXXXXXX"}就表示消息发送成功啦。 -我们可以再IDE控制台中看到输出的结果, -```text -发送响应:MsgId:AC100AB660C618B4AAC2XXXXXXXX,发送状态:SEND_OK -接收到了消息:hello -``` -这时候我们的整合基本上就完成啦。 - -具体代码可以在github获取哦。SpringBootRocketMqDemo@github](https://github.com/xiaour/SpringBootDemo/tree/master/SpringBootRocketMqDemo)获取哦。 \ No newline at end of file diff --git a/SpringBootRocketMqDemo/mvnw b/SpringBootRocketMqDemo/mvnw deleted file mode 100755 index 5bf251c..0000000 --- a/SpringBootRocketMqDemo/mvnw +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/SpringBootRocketMqDemo/mvnw.cmd b/SpringBootRocketMqDemo/mvnw.cmd deleted file mode 100644 index 019bd74..0000000 --- a/SpringBootRocketMqDemo/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/SpringBootRocketMqDemo/pom.xml b/SpringBootRocketMqDemo/pom.xml deleted file mode 100644 index d02e456..0000000 --- a/SpringBootRocketMqDemo/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - - com.github.xiaour - rocketmqDemo - 0.0.1-SNAPSHOT - SpringBootRocketmqDemo - Demo project for RocketMQ - jar - - - org.springframework.boot - spring-boot-starter-parent - 2.0.4.RELEASE - - - - - UTF-8 - UTF-8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - org.apache.rocketmq - rocketmq-client - 4.3.0 - - - org.springframework.boot - spring-boot-starter-web - 2.5.12 - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - diff --git a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplication.java b/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplication.java deleted file mode 100644 index 3c4eb4c..0000000 --- a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.xiaour.spring.boot.rocketmq; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringBootRocketmqDemoApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringBootRocketmqDemoApplication.class, args); - } -} diff --git a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/consumer/Consumer.java b/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/consumer/Consumer.java deleted file mode 100644 index d895994..0000000 --- a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/consumer/Consumer.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.xiaour.spring.boot.rocketmq.consumer; - -import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; -import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; -import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; -import org.apache.rocketmq.common.consumer.ConsumeFromWhere; -import org.apache.rocketmq.common.message.Message; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.CommandLineRunner; - -import org.springframework.stereotype.Component; - -/** - * @Author: Xiaour - * @Description:消费者 - * @Date: 2018/8/9 14:51 - */ - -@Component -public class Consumer implements CommandLineRunner { - - /** - * 消费者 - */ - @Value("${apache.rocketmq.consumer.pushConsumer}") - private String pushConsumer; - - /** - * NameServer 地址 - */ - @Value("${apache.rocketmq.namesrvAddr}") - private String namesrvAddr; - - - /** - * 初始化RocketMq的监听信息,渠道信息 - */ - public void messageListener(){ - - DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("SpringBootRocketMqGroup"); - - consumer.setNamesrvAddr(namesrvAddr); - try { - - // 订阅PushTopic下Tag为push的消息,都订阅消息 - consumer.subscribe("PushTopic", "push"); - - // 程序第一次启动从消息队列头获取数据 - consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); - //可以修改每次消费消息的数量,默认设置是每次消费一条 - consumer.setConsumeMessageBatchMaxSize(1); - - //在此监听中消费信息,并返回消费的状态信息 - consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> { - - // 会把不同的消息分别放置到不同的队列中 - for(Message msg:msgs){ - - System.out.println("接收到了消息:"+new String(msg.getBody())); - } - return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; - }); - - consumer.start(); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void run(String... args) throws Exception { - this.messageListener(); - } -} diff --git a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/controller/TestController.java b/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/controller/TestController.java deleted file mode 100644 index 9bf1eb0..0000000 --- a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/controller/TestController.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.xiaour.spring.boot.rocketmq.controller; - -import com.xiaour.spring.boot.rocketmq.producer.Producer; -import org.apache.rocketmq.client.exception.MQBrokerException; -import org.apache.rocketmq.client.exception.MQClientException; -import org.apache.rocketmq.remoting.exception.RemotingException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.io.UnsupportedEncodingException; - -/** - * @Author: Xiaour - * @Description: 这里是为了测试 - * @Date: 2018/8/9 15:16 - */ -@RestController -public class TestController { - @Autowired - private Producer producer; - - @RequestMapping("/push") - public String pushMsg(String msg){ - try { - return producer.send("PushTopic","push",msg); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (RemotingException e) { - e.printStackTrace(); - } catch (MQClientException e) { - e.printStackTrace(); - } catch (MQBrokerException e) { - e.printStackTrace(); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - return "ERROR"; - } -} diff --git a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/producer/Producer.java b/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/producer/Producer.java deleted file mode 100644 index cb7440b..0000000 --- a/SpringBootRocketMqDemo/src/main/java/com/xiaour/spring/boot/rocketmq/producer/Producer.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.xiaour.spring.boot.rocketmq.producer; - -import org.apache.commons.lang3.time.StopWatch; -import org.apache.rocketmq.client.exception.MQBrokerException; -import org.apache.rocketmq.client.exception.MQClientException; -import org.apache.rocketmq.client.producer.DefaultMQProducer; -import org.apache.rocketmq.client.producer.SendResult; -import org.apache.rocketmq.common.message.Message; -import org.apache.rocketmq.remoting.common.RemotingHelper; -import org.apache.rocketmq.remoting.exception.RemotingException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import java.io.UnsupportedEncodingException; - -/** - * @Author: Xiaour - * @Description:生产者 - * @Date: 2018/8/9 14:52 - */ - -@Component -public class Producer { - - /** - * 生产者的组名 - */ - @Value("${apache.rocketmq.producer.producerGroup}") - private String producerGroup; - - private DefaultMQProducer producer; - /** - * NameServer 地址 - */ - @Value("${apache.rocketmq.namesrvAddr}") - private String namesrvAddr; - - @PostConstruct - public void defaultMQProducer() { - - //生产者的组名 - producer= new DefaultMQProducer(producerGroup); - //指定NameServer地址,多个地址以 ; 隔开 - producer.setNamesrvAddr(namesrvAddr); - producer.setVipChannelEnabled(false); - try { - producer.start(); - System.out.println("-------->:producer启动了"); - } catch (MQClientException e) { - e.printStackTrace(); - } - } - - public String send(String topic,String tags,String body) throws InterruptedException, RemotingException, MQClientException, MQBrokerException, UnsupportedEncodingException { - Message message = new Message(topic, tags, body.getBytes(RemotingHelper.DEFAULT_CHARSET)); - StopWatch stop = new StopWatch(); - stop.start(); - SendResult result = producer.send(message); - System.out.println("发送响应:MsgId:" + result.getMsgId() + ",发送状态:" + result.getSendStatus()); - stop.stop(); - return "{\"MsgId\":\""+result.getMsgId()+"\"}"; - } - -} diff --git a/SpringBootRocketMqDemo/src/main/resources/application.yml b/SpringBootRocketMqDemo/src/main/resources/application.yml deleted file mode 100644 index 115f0d8..0000000 --- a/SpringBootRocketMqDemo/src/main/resources/application.yml +++ /dev/null @@ -1,7 +0,0 @@ -apache: - rocketmq: - consumer: - pushConsumer: XiaourPushConsumer - producer: - producerGroup: Xiaour - namesrvAddr: 192.168.2.5:9876 \ No newline at end of file diff --git a/SpringBootRocketMqDemo/src/test/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplicationTests.java b/SpringBootRocketMqDemo/src/test/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplicationTests.java deleted file mode 100644 index 94a38e5..0000000 --- a/SpringBootRocketMqDemo/src/test/java/com/xiaour/spring/boot/rocketmq/SpringBootRocketmqDemoApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.xiaour.spring.boot.rocketmq; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringBootRocketmqDemoApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/SpringWebFluxDemo/.gitignore b/SpringWebFluxDemo/.gitignore deleted file mode 100644 index ba5cb5c..0000000 --- a/SpringWebFluxDemo/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -HELP.md -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -/build/ diff --git a/SpringWebFluxDemo/pom.xml b/SpringWebFluxDemo/pom.xml deleted file mode 100644 index f98a09c..0000000 --- a/SpringWebFluxDemo/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.1.3.RELEASE - - - com.github.xiaour - fluxDemo - 0.0.1-SNAPSHOT - SpringWebFluxDemo - Demo project for Web Flux - - - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-webflux - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/SpringWebFluxDemoApplication.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/SpringWebFluxDemoApplication.java deleted file mode 100644 index d13a52c..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/SpringWebFluxDemoApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.github.xiaour.flux; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringWebFluxDemoApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringWebFluxDemoApplication.class, args); - } - -} diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/HelloWorlController.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/HelloWorlController.java deleted file mode 100644 index f45ae29..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/HelloWorlController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.github.xiaour.flux.controller; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Mono; - -/** - * @Author: cityuu@163.com - * @Date: 2019-02-27 16:26 - * @version: v1.0 - * @Description: 入门案例 - */ - -@RestController -@RequestMapping("/") -public class HelloWorlController { - - @GetMapping("hello") - public Mono hello(){ - return Mono.just("hello World!"); - } - -} diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/SSEController.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/SSEController.java deleted file mode 100644 index dbbba46..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/SSEController.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.github.xiaour.flux.controller; - -import io.netty.util.internal.ThreadLocalRandom; -import org.springframework.http.codec.ServerSentEvent; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import reactor.core.publisher.Flux; -import reactor.util.function.Tuples; - -import java.time.Duration; - -/** - * @Author: cityuu@163.com - * @Date: 2019-02-27 16:37 - * @version: v1.0 - * @Description: 服务器推送接口 - */ -@RestController -@RequestMapping("/sse") -public class SSEController { - - @GetMapping("/randomNumbers") - public Flux> randomNumbers() { - return Flux.interval(Duration.ofSeconds(2)) - .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt())) - .map(data -> ServerSentEvent.builder() - .event("random") - .id(Long.toString(data.getT1())) - .data(data.getT2()) - .build()); - } - -} diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/UserController.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/UserController.java deleted file mode 100644 index 823df9b..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/controller/UserController.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.github.xiaour.flux.controller; - -import com.github.xiaour.flux.entity.User; -import com.github.xiaour.flux.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.util.Objects; - -/** - * @Author: cityuu@163.com - * @Date: 2019-02-27 16:33 - * @version: v1.0 - * @Description: 用户管理接口 - */ -@RestController -@RequestMapping("/user") -public class UserController { - - @Autowired - private UserService userService; - - - @GetMapping("") - public Flux list() { - return userService.list(); - } - - @GetMapping("/{id}") - public Mono getById(@PathVariable("id") final String id) { - return this.userService.getById(id); - } - - @PostMapping("") - public Mono create(@RequestBody final User user) { - return this.userService.createOrUpdate(user); - } - - @PutMapping("/{id}") - public Mono update(@PathVariable("id") final String id, @RequestBody final User user) { - Objects.requireNonNull(user); - user.setId(id); - return this.userService.createOrUpdate(user); - } - - @DeleteMapping("/{id}") - public Mono delete(@PathVariable("id") final String id) { - return this.userService.delete(id); - } - -} diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/entity/User.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/entity/User.java deleted file mode 100644 index 9a9f9a5..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/entity/User.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.github.xiaour.flux.entity; - -/** - * @Author: cityuu@suiyueyule.com - * @Date: 2019-02-27 16:31 - * @version: v1.0 - * @Description: - */ -public class User { - - private String id; - - private String name; - - private Integer age; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } -} diff --git a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/service/UserService.java b/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/service/UserService.java deleted file mode 100644 index 0d39680..0000000 --- a/SpringWebFluxDemo/src/main/java/com/github/xiaour/flux/service/UserService.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.github.xiaour.flux.service; - -import com.github.xiaour.flux.entity.User; -import org.springframework.stereotype.Service; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @Author: cityuu@suiyueyule.com - * @Date: 2019-02-27 16:30 - * @version: v1.0 - * @Description: - */ -@Service -public class UserService { - - private final Map data = new ConcurrentHashMap<>(); - - public Flux list() { - return Flux.fromIterable(this.data.values()); - } - - public Flux getById(final Flux ids) { - return ids.flatMap(id -> Mono.justOrEmpty(this.data.get(id))); - } - - public Mono getById(final String id) { - return Mono.justOrEmpty(this.data.get(id)); - } - - public Mono createOrUpdate(final User user) { - this.data.put(user.getId(), user); - return Mono.just(user); - } - - public Mono delete(final String id) { - return Mono.justOrEmpty(this.data.remove(id)); - } - - -} diff --git a/SpringWebFluxDemo/src/main/resources/application.properties b/SpringWebFluxDemo/src/main/resources/application.properties deleted file mode 100644 index 8b13789..0000000 --- a/SpringWebFluxDemo/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/SpringWebFluxDemo/src/test/java/com/github/xiaour/flux/SpringWebFluxDemoApplicationTests.java b/SpringWebFluxDemo/src/test/java/com/github/xiaour/flux/SpringWebFluxDemoApplicationTests.java deleted file mode 100644 index d2b3784..0000000 --- a/SpringWebFluxDemo/src/test/java/com/github/xiaour/flux/SpringWebFluxDemoApplicationTests.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.github.xiaour.flux; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class SpringWebFluxDemoApplicationTests { - - @Test - public void contextLoads() { - } - -} diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 028c717..0000000 --- a/pom.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - 4.0.0 - - com.github.xiaour - com.xiaour.spring.boot - 0.0.1-SNAPSHOT - SpringBootDemo - SpringBoot set demo - pom - - - SpringBootDemo - SpringBootDemoV2 - SpringBootDemoV3 - SpringBootKafkaDemo - SpringBootRocketMqDemo - SpringWebFluxDemo - - - - - 17 - - -