springcloud自动生成脚手架搭建(二)

完成之后的前台页面展示:

测试地址 :dota2info.cn/index                

springcloud自动生成脚手架搭建(二)_第1张图片

1.配置pom.xml

  
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter

        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            1.0.4
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            ${mybatis.spring.boot.version}
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
            com.alibaba
            druid
            ${druid.version}
        
        
            commons-lang
            commons-lang
            ${commons.lang.version}
        
        
            commons-io
            commons-io
            ${commons.io.version}
        
        
            commons-configuration
            commons-configuration
            ${commons.configuration.version}
        

        
            com.alibaba
            fastjson
            ${fastjson.version}
        
        
            velocity
            org.apache.velocity
            2.0
        
        
            com.baomidou
            mybatis-plus
            2.1.7
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            net.sourceforge.nekohtml
            nekohtml
            1.9.22
        
        
            org.apache.velocity
            velocity-engine-core
            2.0
        
        
            com.gameley
            gameley-common
            1.0
        
        
            org.dom4j
            dom4j
            2.0.0
        
        
            org.springframework
            spring-test
            4.3.13.RELEASE
        
        
            org.springframework.boot
            spring-boot-test
            1.5.5.RELEASE
        
        
            org.springframework.boot
            spring-boot-test
        

数据库使用mysql,使用mybatis-plus作为连接数据库工具

2.配置application.yml

# Tomcat
server:
    tomcat:
        max-threads: 10
        min-spare-threads: 10
    port: 7777

# mysql
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/ag_admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false
        username: root
        password: 123456
    jackson:
        time-zone: GMT+8
        date-format: yyyy-MM-dd HH:mm:ss
    thymeleaf:
        mode: LEGACYHTML5
        cache: false

# Mybatis配置
mybatis:
    mapperLocations: classpath:mapper/*.xml
#mybatis
mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.gameley.generator.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: cn.jeefast.xxx
    #逻辑删除配置
    logic-delete-value: 0
    logic-not-delete-value: 1
    #自定义填充策略接口实现
    #meta-object-handler: cn.jeefast.xxx
    #自定义SQL注入器
    #sql-injector: cn.jeefast.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false


3.编写主要的生成工具类:

package com.gameley.generator.utils;

import com.baomidou.mybatisplus.plugins.Page;
import com.gameley.generator.entity.ColumnEntity;
import com.gameley.generator.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 *
 * @author chenshun
 * @email [email protected]
 * @date 2016年12月19日 下午11:40:24
 */
public class GeneratorUtils {

    public static List getTemplates() {
        List templates = new ArrayList();
        templates.add("template/index.vue.vm");
        templates.add("template/mapper.xml.vm");
        templates.add("template/entity.java.vm");
        templates.add("template/mapper.java.vm");
        templates.add("template/controller.java.vm");
        templates.add("template/service.java.vm");
        templates.add("template/serviceImpl.java.vm");
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(Map table,
                                     List> columns, ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();

        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));
        //表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List columsList = new ArrayList<>();
        for (Map column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型,转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //没主键,则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        //封装模板数据
        Map map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("moduleName", config.getString("mainModule"));
        map.put("secondModuleName", toLowerCaseFirstOne(className));
        map.put("enableCache",false);  //不开启二级缓存
        map.put("baseResultMap",true);

        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), config.getString("package"), config.getString("mainModule"))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RuntimeException("渲染模板失败,表名:" + tableEntity.getTableName(), e);
            }
        }
    }


    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RuntimeException("获取配置文件失败,", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        String frontPath = "ui" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }

        if (template.contains("index.vue.vm")) {
            return frontPath + "views" + File.separator + moduleName + File.separator + toLowerCaseFirstOne(className) + File.separator + "index.vue";
        }

        if (template.contains("service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }
        if (template.contains("mapper.java.vm")) {
            return packagePath + "dao" + File.separator + className + "Dao.java";
        }
        if (template.contains("entity.java.vm")) {
            return packagePath + "entity" + File.separator + className + ".java";
        }
        if (template.contains("controller.java.vm")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }
        if (template.contains("serviceImpl.java.vm")) {
            return packagePath + "service" + File.separator +"impl"+File.separator+ className + "ServiceImpl.java";
        }
        if (template.contains("mapper.xml.vm")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
        }

        return null;
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

}
其余部分及生成模板详见:https://gitee.com/lwydyby/springcloud-adplatform

----  2018-01-10------

增加springcloud-bus,以实现自动配置

 1.在两个工程的pom.xml中引入



   org.springframework.cloud
   spring-cloud-starter-bus-amqp



   org.springframework.boot
   spring-boot-starter-actuator
2.在config的配置中加入

 

  rabbitmq:
        host: rabbitmq   # 登录 Rabbitmq 后台管理页面地址为:http://localhost:15672
        port: 5672
        username: guest   # 默认账户
        password: guest   # 默认密码
3.在generator增加config配置类 (这里只做了对数据库的动态配置)

 

package com.gameley.generator.config;

import java.sql.SQLException;

import javax.sql.DataSource;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * 配置数据库
 * @author wwmxd
 * @version 1.2.0
 */
@Slf4j
@Configuration
@RefreshScope
public class DruidConfiguration {
    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
  


    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    @RefreshScope
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        return datasource;
    }
}
4.配置github或者码云上的项目管理,增加WebHooks,来主动推送更新

增加的url,例如:

  http://{ip}:8888/bus/refresh

如需设置密码,则在config中增加配置

encrypt:
  key: 123456

   


  

你可能感兴趣的:(springcloud项目搭建)