From d1e50ef7ecd095188a1964be01e6c6746454a20d Mon Sep 17 00:00:00 2001 From: lsy <18332763730@163.com> Date: Mon, 31 Jul 2017 08:34:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0mybatis=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bash.sh | 1 + bash/docker_shipyarn_run.sh | 5 + bash/docker_shipyarn_stop.sh | 5 + code_check.xml | 235 ++++++++++++++++++ common/.gitignore | 32 +++ common/pom.xml | 137 ++++++++++ .../micro/fast/common/CommonApplication.java | 15 ++ .../com/micro/fast/common/util/AESUtil.java | 147 +++++++++++ .../com/micro/fast/common/util/JdbcUtil.java | 89 +++++++ .../common/util/MybatisGeneratorUtil.java | 173 +++++++++++++ .../micro/fast/common/util/StringUtil.java | 157 ++++++++++++ .../micro/fast/common/util/VelocityUtil.java | 68 +++++ .../src/main/resources/application.properties | 0 .../main/resources/templates/Controller.vm | 25 ++ .../src/main/resources/templates/Service.vm | 13 + .../main/resources/templates/ServiceImpl.vm | 29 +++ .../main/resources/templates/ServiceMock.vm | 14 ++ .../resources/templates/generatorConfig.vm | 74 ++++++ .../fast/common/CommonApplicationTests.java | 16 ++ docker-compose.yml | 1 + .../server/EurekaServerApplication.java | 7 +- .../server2/EurekaServer2Application.java | 8 +- .../com/micro/fast/upms/UpmsApplication.java | 6 +- 23 files changed, 1247 insertions(+), 10 deletions(-) create mode 100644 bash.sh create mode 100644 bash/docker_shipyarn_run.sh create mode 100644 bash/docker_shipyarn_stop.sh create mode 100644 code_check.xml create mode 100644 common/.gitignore create mode 100644 common/pom.xml create mode 100644 common/src/main/java/com/micro/fast/common/CommonApplication.java create mode 100644 common/src/main/java/com/micro/fast/common/util/AESUtil.java create mode 100644 common/src/main/java/com/micro/fast/common/util/JdbcUtil.java create mode 100644 common/src/main/java/com/micro/fast/common/util/MybatisGeneratorUtil.java create mode 100644 common/src/main/java/com/micro/fast/common/util/StringUtil.java create mode 100644 common/src/main/java/com/micro/fast/common/util/VelocityUtil.java create mode 100644 common/src/main/resources/application.properties create mode 100644 common/src/main/resources/templates/Controller.vm create mode 100644 common/src/main/resources/templates/Service.vm create mode 100644 common/src/main/resources/templates/ServiceImpl.vm create mode 100644 common/src/main/resources/templates/ServiceMock.vm create mode 100644 common/src/main/resources/templates/generatorConfig.vm create mode 100644 common/src/test/java/com/micro/fast/common/CommonApplicationTests.java diff --git a/bash.sh b/bash.sh new file mode 100644 index 0000000..f1f641a --- /dev/null +++ b/bash.sh @@ -0,0 +1 @@ +#!/usr/bin/env bash diff --git a/bash/docker_shipyarn_run.sh b/bash/docker_shipyarn_run.sh new file mode 100644 index 0000000..fd134e1 --- /dev/null +++ b/bash/docker_shipyarn_run.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# 开启shipyarnf服务 +echo "准备开始" +curl -s https://shipyard-project.com/deploy | bash -s +echo "开启成功" \ No newline at end of file diff --git a/bash/docker_shipyarn_stop.sh b/bash/docker_shipyarn_stop.sh new file mode 100644 index 0000000..6bc72a6 --- /dev/null +++ b/bash/docker_shipyarn_stop.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# 关闭shipyarnf服务 +echo "准备关闭" +curl -sSL https://shipyard-project.com/deploy| ACTION=remove bash -s +echo "关闭成功" diff --git a/code_check.xml b/code_check.xml new file mode 100644 index 0000000..d0ccbd2 --- /dev/null +++ b/code_check.xml @@ -0,0 +1,235 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/common/.gitignore b/common/.gitignore new file mode 100644 index 0000000..7a8343d --- /dev/null +++ b/common/.gitignore @@ -0,0 +1,32 @@ +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/ + +### maven ### +target +out +.mvn +mvnw +mvnw.cmd +classes diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 0000000..a607881 --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,137 @@ + + + 4.0.0 + + com.micro.fast + common + 0.0.1-SNAPSHOT + jar + + common + common + + + org.springframework.boot + spring-boot-starter-parent + 1.5.4.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + Dalston.SR2 + 1.8 + 1.8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter-bus-amqp + + + org.springframework.cloud + spring-cloud-starter-config + + + org.springframework.cloud + spring-cloud-starter-eureka + + + org.springframework.cloud + spring-cloud-starter-feign + + + org.springframework.cloud + spring-cloud-starter-hystrix + + + org.springframework.cloud + spring-cloud-starter-ribbon + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + org.springframework.cloud + spring-cloud-starter-zipkin + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-freemarker + + + org.springframework.boot + spring-boot-starter-web + + + + mysql + mysql-connector-java + runtime + + + io.zipkin.java + zipkin-autoconfigure-ui + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.mybatis.generator + mybatis-generator-core + 1.3.5 + + + org.apache.velocity + velocity + 1.7 + + + + commons-io + commons-io + 2.4 + + + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/common/src/main/java/com/micro/fast/common/CommonApplication.java b/common/src/main/java/com/micro/fast/common/CommonApplication.java new file mode 100644 index 0000000..18aee0a --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/CommonApplication.java @@ -0,0 +1,15 @@ +package com.micro.fast.common; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.SpringCloudApplication; +import org.springframework.cloud.netflix.feign.EnableFeignClients; + +@SpringCloudApplication +@EnableFeignClients +public class CommonApplication { + + public static void main(String[] args) { + SpringApplication.run(CommonApplication.class, args); + } +} diff --git a/common/src/main/java/com/micro/fast/common/util/AESUtil.java b/common/src/main/java/com/micro/fast/common/util/AESUtil.java new file mode 100644 index 0000000..a504b19 --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/util/AESUtil.java @@ -0,0 +1,147 @@ +package com.micro.fast.common.util; + + + +import javax.crypto.*; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; +/** + * AES加解密工具类 + * Created by shuzheng on 2017/2/5. + */ +public class AESUtil { + /** + * 注释 . + */ + private static final String encodeRules = "zheng"; + + /** + * 加密 + * 1.构造密钥生成器 + * 2.根据ecnodeRules规则初始化密钥生成器 + * 3.产生密钥 + * 4.创建和初始化密码器 + * 5.内容加密 + * 6.返回字符串. + */ + private static String AESEncode(String content) { + try { + //1.构造密钥生成器,指定为AES算法,不区分大小写 + KeyGenerator keygen = KeyGenerator.getInstance("AES"); + //2.根据ecnodeRules规则初始化密钥生成器 + //生成一个128位的随机源,根据传入的字节数组 + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(encodeRules.getBytes()); + keygen.init(128, random); + //3.产生原始对称密钥 + SecretKey original_key = keygen.generateKey(); + //4.获得原始对称密钥的字节数组 + byte[] raw = original_key.getEncoded(); + //5.根据字节数组生成AES密钥 + SecretKey key = new SecretKeySpec(raw, "AES"); + //6.根据指定算法AES自成密码器 + Cipher cipher = Cipher.getInstance("AES"); + //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY + cipher.init(Cipher.ENCRYPT_MODE, key); + //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码 + byte[] byte_encode = content.getBytes("utf-8"); + //9.根据密码器的初始化方式--加密:将数据加密 + byte[] byte_AES = cipher.doFinal(byte_encode); + //10.将加密后的数据转换为字符串 + //这里用Base64Encoder中会找不到包 + //解决办法: + //在项目的Build path中先移除JRE System Library,再添加库JRE System Library,重新编译后就一切正常了。 + String AES_encode = new String(new BASE64Encoder().encode(byte_AES)); + //11.将字符串返回 + return AES_encode; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (NoSuchPaddingException e) { + e.printStackTrace(); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (IllegalBlockSizeException e) { + e.printStackTrace(); + } catch (BadPaddingException e) { + e.printStackTrace(); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + //如果有错就返加nulll + return null; + } + + /** + * 解密 + * 解密过程: + * 1.同加密1-4步 + * 2.将加密后的字符串反纺成byte[]数组 + * 3.将加密内容解密 + */ + public static String AESDecode(String content) { + try { + //1.构造密钥生成器,指定为AES算法,不区分大小写 + KeyGenerator keygen = KeyGenerator.getInstance("AES"); + //2.根据ecnodeRules规则初始化密钥生成器 + //生成一个128位的随机源,根据传入的字节数组 + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(encodeRules.getBytes()); + keygen.init(128, random); + //3.产生原始对称密钥 + SecretKey original_key = keygen.generateKey(); + //4.获得原始对称密钥的字节数组 + byte[] raw = original_key.getEncoded(); + //5.根据字节数组生成AES密钥 + SecretKey key = new SecretKeySpec(raw, "AES"); + //6.根据指定算法AES自成密码器 + Cipher cipher = Cipher.getInstance("AES"); + //7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY + cipher.init(Cipher.DECRYPT_MODE, key); + //8.将加密并编码后的内容解码成字节数组 + byte[] byte_content = new BASE64Decoder().decodeBuffer(content); + /* + * 解密 + */ + byte[] byte_decode = cipher.doFinal(byte_content); + String AES_decode = new String(byte_decode, "utf-8"); + return AES_decode; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (NoSuchPaddingException e) { + e.printStackTrace(); + } catch (InvalidKeyException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (IllegalBlockSizeException e) { + throw new RuntimeException("兄弟,配置文件中的密码需要使用AES加密,请使用com.zheng.common.util.AESUtil工具类修改这些值!"); + //e.printStackTrace(); + } catch (BadPaddingException e) { + e.printStackTrace(); + } + //如果有错就返加nulll + return null; + } + + public static void main(String[] args) { + String[] keys = { + "", "123456" + }; + System.out.println("key | AESEncode | AESDecode"); + for (String key : keys) { + System.out.print(key + " | "); + String encryptString = AESEncode(key); + System.out.print(encryptString + " | "); + String decryptString = AESDecode(encryptString); + System.out.println(decryptString); + } + } + +} diff --git a/common/src/main/java/com/micro/fast/common/util/JdbcUtil.java b/common/src/main/java/com/micro/fast/common/util/JdbcUtil.java new file mode 100644 index 0000000..8cebb93 --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/util/JdbcUtil.java @@ -0,0 +1,89 @@ +package com.micro.fast.common.util; + +import java.sql.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * JDBC工具类 + * Created by ZhangShuzheng on 2017/1/10. + */ +public class JdbcUtil { + + // 定义数据库的链接 + private Connection conn; + // 定义sql语句的执行对象 + private PreparedStatement pstmt; + // 定义查询返回的结果集合 + private ResultSet rs; + + // 初始化 + public JdbcUtil(String driver, String url, String username, String password) { + try { + Class.forName(driver); + conn = DriverManager.getConnection(url, username, password); + System.out.println("数据库连接成功"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // 更新数据 + public boolean updateByParams(String sql, List params) throws SQLException { + // 影响行数 + int result = -1; + pstmt = conn.prepareStatement(sql); + int index = 1; + // 填充sql语句中的占位符 + if (null != params && !params.isEmpty()) { + for (int i = 0; i < params.size(); i ++) { + pstmt.setObject(index ++, params.get(i)); + } + } + result = pstmt.executeUpdate(); + return result > 0 ? true : false; + } + + // 查询多条记录 + public List selectByParams(String sql, List params) throws SQLException { + List list = new ArrayList<> (); + int index = 1; + pstmt = conn.prepareStatement(sql); + if (null != params && !params.isEmpty()) { + for (int i = 0; i < params.size(); i ++) { + pstmt.setObject(index++, params.get(i)); + } + } + rs = pstmt.executeQuery(); + ResultSetMetaData metaData = rs.getMetaData(); + int cols_len = metaData.getColumnCount(); + while (rs.next()) { + Map map = new HashMap(); + for (int i = 0; i < cols_len; i ++) { + String cols_name = metaData.getColumnName(i + 1); + Object cols_value = rs.getObject(cols_name); + if (null == cols_value) { + cols_value = ""; + } + map.put(cols_name, cols_value); + } + list.add(map); + } + return list; + } + + // 释放连接 + public void release() { + try { + if (null != rs) rs.close(); + if (null != pstmt) pstmt.close(); + if (null != conn) conn.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + System.out.println("释放数据库连接"); + } + +} diff --git a/common/src/main/java/com/micro/fast/common/util/MybatisGeneratorUtil.java b/common/src/main/java/com/micro/fast/common/util/MybatisGeneratorUtil.java new file mode 100644 index 0000000..976f723 --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/util/MybatisGeneratorUtil.java @@ -0,0 +1,173 @@ +package com.micro.fast.common.util; + +import org.apache.commons.lang.ObjectUtils; +import org.apache.velocity.VelocityContext; +import org.mybatis.generator.api.MyBatisGenerator; +import org.mybatis.generator.config.Configuration; +import org.mybatis.generator.config.xml.ConfigurationParser; +import org.mybatis.generator.internal.DefaultShellCallback; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.*; + +import static com.micro.fast.common.util.StringUtil.lineToHump; + + +/** + * 代码生成类 + * Created by ZhangShuzheng on 2017/1/10. + */ +public class MybatisGeneratorUtil { + + // generatorConfig模板路径 + private static String generatorConfig_vm = "/templates/generatorConfig.vm"; + // Service模板路径 + private static String service_vm = "/templates/Service.vm"; + // ServiceMock模板路径 + private static String serviceMock_vm = "/templates/ServiceMock.vm"; + // ServiceImpl模板路径 + private static String serviceImpl_vm = "/templates/ServiceImpl.vm"; + + /** + * 根据模板生成generatorConfig.xml文件 + * @param jdbc_driver 驱动路径 + * @param jdbc_url 链接 + * @param jdbc_username 帐号 + * @param jdbc_password 密码 + * @param module 项目模块 + * @param database 数据库 + * @param table_prefix 表前缀 + * @param package_name 包名 + */ + public static void generator( + String jdbc_driver, + String jdbc_url, + String jdbc_username, + String jdbc_password, + String module, + String database, + String table_prefix, + String package_name, + Map last_insert_id_tables) throws Exception{ + + generatorConfig_vm = MybatisGeneratorUtil.class.getResource(generatorConfig_vm).getPath().replaceFirst("/", ""); + service_vm = MybatisGeneratorUtil.class.getResource(service_vm).getPath().replaceFirst("/", ""); + serviceMock_vm = MybatisGeneratorUtil.class.getResource(serviceMock_vm).getPath().replaceFirst("/", ""); + serviceImpl_vm = MybatisGeneratorUtil.class.getResource(serviceImpl_vm).getPath().replaceFirst("/", ""); + + String targetProject = module + "/" + module + "-dao"; + String basePath = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "").replace(targetProject, "").replaceFirst("/", ""); + String generatorConfig_xml = MybatisGeneratorUtil.class.getResource("/").getPath().replace("/target/classes/", "") + "/src/main/resources/generatorConfig.xml"; + targetProject = basePath + targetProject; + String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "' AND table_name LIKE '" + table_prefix + "_%';"; + + System.out.println("========== 开始生成generatorConfig.xml文件 =========="); + List> tables = new ArrayList<>(); + try { + VelocityContext context = new VelocityContext(); + Map table; + + // 查询定制前缀项目的所有表 + JdbcUtil jdbcUtil = new JdbcUtil(jdbc_driver, jdbc_url, jdbc_username, AESUtil.AESDecode(jdbc_password)); + List result = jdbcUtil.selectByParams(sql, null); + for (Map map : result) { + System.out.println(map.get("TABLE_NAME")); + table = new HashMap<>(); + table.put("table_name", map.get("TABLE_NAME")); + table.put("model_name", lineToHump(ObjectUtils.toString(map.get("TABLE_NAME")))); + tables.add(table); + } + jdbcUtil.release(); + + String targetProject_sqlMap = basePath + module + "/" + module + "-rpc-service"; + context.put("tables", tables); + context.put("generator_javaModelGenerator_targetPackage", package_name + ".dao.model"); + context.put("generator_sqlMapGenerator_targetPackage", package_name + ".dao.mapper"); + context.put("generator_javaClientGenerator_targetPackage", package_name + ".dao.mapper"); + context.put("targetProject", targetProject); + context.put("targetProject_sqlMap", targetProject_sqlMap); + context.put("generator_jdbc_password", AESUtil.AESDecode(jdbc_password)); + context.put("last_insert_id_tables", last_insert_id_tables); + VelocityUtil.generate(generatorConfig_vm, generatorConfig_xml, context); + // 删除旧代码 + deleteDir(new File(targetProject + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/model")); + deleteDir(new File(targetProject + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/mapper")); + deleteDir(new File(targetProject_sqlMap + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/dao/mapper")); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("========== 结束生成generatorConfig.xml文件 =========="); + + System.out.println("========== 开始运行MybatisGenerator =========="); + List warnings = new ArrayList<>(); + File configFile = new File(generatorConfig_xml); + ConfigurationParser cp = new ConfigurationParser(warnings); + Configuration config = cp.parseConfiguration(configFile); + DefaultShellCallback callback = new DefaultShellCallback(true); + MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); + myBatisGenerator.generate(null); + for (String warning : warnings) { + System.out.println(warning); + } + System.out.println("========== 结束运行MybatisGenerator =========="); + + System.out.println("========== 开始生成Service =========="); + String ctime = new SimpleDateFormat("yyyy/M/d").format(new Date()); + String servicePath = basePath + module + "/" + module + "-rpc-api" + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/rpc/api"; + String serviceImplPath = basePath + module + "/" + module + "-rpc-service" + "/src/main/java/" + package_name.replaceAll("\\.", "/") + "/rpc/service/impl"; + for (int i = 0; i < tables.size(); i++) { + String model = lineToHump(ObjectUtils.toString(tables.get(i).get("table_name"))); + String service = servicePath + "/" + model + "Service.java"; + String serviceMock = servicePath + "/" + model + "ServiceMock.java"; + String serviceImpl = serviceImplPath + "/" + model + "ServiceImpl.java"; + // 生成service + File serviceFile = new File(service); + if (!serviceFile.exists()) { + VelocityContext context = new VelocityContext(); + context.put("package_name", package_name); + context.put("model", model); + context.put("ctime", ctime); + VelocityUtil.generate(service_vm, service, context); + System.out.println(service); + } + // 生成serviceMock + File serviceMockFile = new File(serviceMock); + if (!serviceMockFile.exists()) { + VelocityContext context = new VelocityContext(); + context.put("package_name", package_name); + context.put("model", model); + context.put("ctime", ctime); + VelocityUtil.generate(serviceMock_vm, serviceMock, context); + System.out.println(serviceMock); + } + // 生成serviceImpl + File serviceImplFile = new File(serviceImpl); + if (!serviceImplFile.exists()) { + VelocityContext context = new VelocityContext(); + context.put("package_name", package_name); + context.put("model", model); + context.put("mapper", StringUtil.toLowerCaseFirstOne(model)); + context.put("ctime", ctime); + VelocityUtil.generate(serviceImpl_vm, serviceImpl, context); + System.out.println(serviceImpl); + } + } + System.out.println("========== 结束生成Service =========="); + + System.out.println("========== 开始生成Controller =========="); + System.out.println("========== 结束生成Controller =========="); + } + + // 递归删除非空文件夹 + public static void deleteDir(File dir) { + if (dir.isDirectory()) { + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + deleteDir(files[i]); + } + } + dir.delete(); + } + +} diff --git a/common/src/main/java/com/micro/fast/common/util/StringUtil.java b/common/src/main/java/com/micro/fast/common/util/StringUtil.java new file mode 100644 index 0000000..62347a1 --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/util/StringUtil.java @@ -0,0 +1,157 @@ +package com.micro.fast.common.util; + + +import org.apache.commons.lang.StringUtils; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * String 工具类 + * Created by shuzheng on 2016/12/07. + */ +public class StringUtil { + + private static Pattern linePattern = Pattern.compile("_(\\w)"); + private static Pattern humpPattern = Pattern.compile("[A-Z]"); + + /** + * 下划线转驼峰 + * @param str + * @return + */ + private static String lineToHump(String str) { + if (null == str || "".equals(str)) { + return str; + } + str = str.toLowerCase(); + Matcher matcher = linePattern.matcher(str); + StringBuffer sb = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); + } + matcher.appendTail(sb); + + str = sb.toString(); + str = str.substring(0, 1).toUpperCase() + str.substring(1); + + return str; + } + + /** + * 驼峰转下划线(简单写法,效率低于{@link #humpToLine2(String)}) + * @param str + * @return + */ + public static String humpToLine(String str) { + return str.replaceAll("[A-Z]", "_$0").toLowerCase(); + } + + /** + * 驼峰转下划线,效率比上面高 + * @param str + * @return + */ + public static String humpToLine2(String str) { + Matcher matcher = humpPattern.matcher(str); + StringBuffer sb = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase()); + } + matcher.appendTail(sb); + return sb.toString(); + } + + /** + * 首字母转小写 + * @param s + * @return + */ + public static String toLowerCaseFirstOne(String s) { + if (StringUtils.isBlank(s)) { + return s; + } + if (Character.isLowerCase(s.charAt(0))) { + return s; + } else { + return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString(); + } + } + + /** + * 首字母转大写 + * @param s + * @return + */ + public static String toUpperCaseFirstOne(String s) { + if (StringUtils.isBlank(s)) { + return s; + } + if (Character.isUpperCase(s.charAt(0))) { + return s; + } else { + return (new StringBuffer()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString(); + } + } + + /** + * object转String + * @param object + * @return + */ + public static String getString(Object object) { + return getString(object, ""); + } + + public static String getString(Object object, String defaultValue) { + if (null == object) { + return defaultValue; + } + try { + return object.toString(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * object转Integer + * @param object + * @return + */ + public static int getInt(Object object) { + return getInt(object, -1); + } + + public static int getInt(Object object, Integer defaultValue) { + if (null == object) { + return defaultValue; + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * object转Boolean + * @param object + * @return + */ + public static boolean getBoolean(Object object) { + return getBoolean(object, false); + } + + public static boolean getBoolean(Object object, Boolean defaultValue) { + if (null == object) { + return defaultValue; + } + try { + return Boolean.parseBoolean(object.toString()); + } catch (Exception e) { + return defaultValue; + } + } + +} diff --git a/common/src/main/java/com/micro/fast/common/util/VelocityUtil.java b/common/src/main/java/com/micro/fast/common/util/VelocityUtil.java new file mode 100644 index 0000000..eade626 --- /dev/null +++ b/common/src/main/java/com/micro/fast/common/util/VelocityUtil.java @@ -0,0 +1,68 @@ +package com.micro.fast.common.util; + +import org.apache.commons.io.output.FileWriterWithEncoding; +import org.apache.commons.lang.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.app.VelocityEngine; + +import java.io.File; +import java.util.Properties; + +/** + * Velocity工具类 + * Created by ZhangShuzheng on 2017/1/10. + */ +public class VelocityUtil { + + /** + * 根据模板生成文件 + * @param inputVmFilePath 模板路径 + * @param outputFilePath 输出文件路径 + * @param context + * @throws Exception + */ + public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception { + try { + Properties properties = new Properties(); + properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath)); + Velocity.init(properties); + //VelocityEngine engine = new VelocityEngine(); + Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8"); + File outputFile = new File(outputFilePath); + FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8"); + template.merge(context, writer); + writer.close(); + } catch (Exception ex) { + throw ex; + } + } + + /** + * 根据文件绝对路径获取目录 + * @param filePath + * @return + */ + public static String getPath(String filePath) { + String path = ""; + if (StringUtils.isNotBlank(filePath)) { + path = filePath.substring(0, filePath.lastIndexOf("/") + 1); + } + return path; + } + + /** + * 根据文件绝对路径获取文件 + * @param filePath + * @return + */ + public static String getFile(String filePath) { + String file = ""; + if (StringUtils.isNotBlank(filePath)) { + file = filePath.substring(filePath.lastIndexOf("/") + 1); + } + return file; + } + +} diff --git a/common/src/main/resources/application.properties b/common/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/common/src/main/resources/templates/Controller.vm b/common/src/main/resources/templates/Controller.vm new file mode 100644 index 0000000..8cdf728 --- /dev/null +++ b/common/src/main/resources/templates/Controller.vm @@ -0,0 +1,25 @@ +package ${groupId}.${module}.${layer}.controller; + +import ${groupId}.common.base.BaseController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * ${modelname}controller + * Created by shuzheng on ${ctime}. + */ +@Controller +@RequestMapping("/manage") +@Api(value = "${modelname}控制器", description = "${modelname}管理") +public class ${model}Controller extends BaseController { + + private static Logger _log = LoggerFactory.getLogger(${model}Controller.class); + + + +} \ No newline at end of file diff --git a/common/src/main/resources/templates/Service.vm b/common/src/main/resources/templates/Service.vm new file mode 100644 index 0000000..d04b42a --- /dev/null +++ b/common/src/main/resources/templates/Service.vm @@ -0,0 +1,13 @@ +package ${package_name}.rpc.api; + +import com.zheng.common.base.BaseService; +import ${package_name}.dao.model.${model}; +import ${package_name}.dao.model.${model}Example; + +/** +* ${model}Service接口 +* Created by shuzheng on ${ctime}. +*/ +public interface ${model}Service extends BaseService<${model}, ${model}Example> { + +} \ No newline at end of file diff --git a/common/src/main/resources/templates/ServiceImpl.vm b/common/src/main/resources/templates/ServiceImpl.vm new file mode 100644 index 0000000..2ffa250 --- /dev/null +++ b/common/src/main/resources/templates/ServiceImpl.vm @@ -0,0 +1,29 @@ +package ${package_name}.rpc.service.impl; + +import com.zheng.common.annotation.BaseService; +import com.zheng.common.base.BaseServiceImpl; +import ${package_name}.dao.mapper.${model}Mapper; +import ${package_name}.dao.model.${model}; +import ${package_name}.dao.model.${model}Example; +import ${package_name}.rpc.api.${model}Service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** +* ${model}Service实现 +* Created by shuzheng on ${ctime}. +*/ +@Service +@Transactional +@BaseService +public class ${model}ServiceImpl extends BaseServiceImpl<${model}Mapper, ${model}, ${model}Example> implements ${model}Service { + + private static Logger _log = LoggerFactory.getLogger(${model}ServiceImpl.class); + + @Autowired + ${model}Mapper ${mapper}Mapper; + +} \ No newline at end of file diff --git a/common/src/main/resources/templates/ServiceMock.vm b/common/src/main/resources/templates/ServiceMock.vm new file mode 100644 index 0000000..b008fba --- /dev/null +++ b/common/src/main/resources/templates/ServiceMock.vm @@ -0,0 +1,14 @@ +package ${package_name}.rpc.api; + +import com.zheng.common.base.BaseServiceMock; +import ${package_name}.dao.mapper.${model}Mapper; +import ${package_name}.dao.model.${model}; +import ${package_name}.dao.model.${model}Example; + +/** +* 降级实现${model}Service接口 +* Created by shuzheng on ${ctime}. +*/ +public class ${model}ServiceMock extends BaseServiceMock<${model}Mapper, ${model}, ${model}Example> implements ${model}Service { + +} diff --git a/common/src/main/resources/templates/generatorConfig.vm b/common/src/main/resources/templates/generatorConfig.vm new file mode 100644 index 0000000..31c4f1b --- /dev/null +++ b/common/src/main/resources/templates/generatorConfig.vm @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #foreach($table in $tables) + #if($last_insert_id_tables.containsKey($!table.table_name) == true) + + +
+ #else +
+ #end + #end +
+
diff --git a/common/src/test/java/com/micro/fast/common/CommonApplicationTests.java b/common/src/test/java/com/micro/fast/common/CommonApplicationTests.java new file mode 100644 index 0000000..cc7bb86 --- /dev/null +++ b/common/src/test/java/com/micro/fast/common/CommonApplicationTests.java @@ -0,0 +1,16 @@ +package com.micro.fast.common; + +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 CommonApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/docker-compose.yml b/docker-compose.yml index 70267b7..c399ff3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,3 +3,4 @@ umps: ports: - "10004:10004" - "20004:20004" +63 diff --git a/eureka-server/src/main/java/com/micro/fast/eureka/server/EurekaServerApplication.java b/eureka-server/src/main/java/com/micro/fast/eureka/server/EurekaServerApplication.java index fe48fea..3e9cc16 100644 --- a/eureka-server/src/main/java/com/micro/fast/eureka/server/EurekaServerApplication.java +++ b/eureka-server/src/main/java/com/micro/fast/eureka/server/EurekaServerApplication.java @@ -1,3 +1,4 @@ + package com.micro.fast.eureka.server; import org.springframework.boot.SpringApplication; @@ -8,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer //开启注册中心相关服务 public class EurekaServerApplication { - public static void main(String[] args) { - SpringApplication.run(EurekaServerApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(EurekaServerApplication.class, args); + } } diff --git a/eureka-server2/src/main/java/com/micro/fast/eureka/server2/EurekaServer2Application.java b/eureka-server2/src/main/java/com/micro/fast/eureka/server2/EurekaServer2Application.java index baa2971..370a552 100644 --- a/eureka-server2/src/main/java/com/micro/fast/eureka/server2/EurekaServer2Application.java +++ b/eureka-server2/src/main/java/com/micro/fast/eureka/server2/EurekaServer2Application.java @@ -5,10 +5,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication -@EnableEurekaServer //开启注册中心的相关服务 +@EnableEurekaServer //开启注册中心的相关服务 public class EurekaServer2Application { - public static void main(String[] args) { - SpringApplication.run(EurekaServer2Application.class, args); - } + public static void main(String[] args) { + SpringApplication.run(EurekaServer2Application.class, args); + } } diff --git a/upms/src/main/java/com/micro/fast/upms/UpmsApplication.java b/upms/src/main/java/com/micro/fast/upms/UpmsApplication.java index 4dbea1b..e770f4b 100644 --- a/upms/src/main/java/com/micro/fast/upms/UpmsApplication.java +++ b/upms/src/main/java/com/micro/fast/upms/UpmsApplication.java @@ -8,7 +8,7 @@ import org.springframework.cloud.netflix.feign.EnableFeignClients; @EnableFeignClients public class UpmsApplication { - public static void main(String[] args) { - SpringApplication.run(UpmsApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(UpmsApplication.class, args); + } }