HRM微服务项目day-01

一. 环境搭建

hrm-parent
    hrm-basic-parent        //项目基本模块
        hrm-basic-utils     //公共工具模块
        hrm-basic-common    //公共代码模块
        
    hrm-support-parent      //项目支撑服务
        hrm-eureka-server-1010  
        hrm-gateway-zuul-1020
        hrm-config-server-1030
        
    hrm-systemmanage-parent 
        hrm-systemmanage-common     //针对系统管理服务公共代码如:domain,query
        hrm-systemmanage-service-2010   //针对于系统管理的微服务

二. 完成hrm-eureka-server-1010的搭建

三. 完成hrm-gateway-zuul-1020的搭建

四. 完成hrm-config-server-1030的搭建

五:完成hrm-systemmanage-service-2010的搭建

1. 导入依赖

2. 注册到注册Eureka

3. 使用代码生成器mybatis-plus完成数据字典的CRUD

  1. 在hrm-basic-parent下创建一个独立的模块mybatis-plus

  2. 导入mybatis-plus的依赖

            
                com.baomidou
                mybatis-plus-boot-starter
                2.2.0
            
            
                org.apache.velocity
                velocity-engine-core
                2.0
            

        
            mysql
            mysql-connector-java
        
  1. 在resources下创建配置文件mybatiesplus-config.properties
#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
#mapper,servier,controller输出目录
OutputDir=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-service-2010/src/main/java

#mapper.xml SQL映射文件目录
OutputDirXml=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-service-2010/src/main/resources
#domain,query输出的目录
OutputDirBase=E:/GitLocalRepository/hrm/hrm-system-parent/hrm-system-common/src/main/java

#设置作者
author=hfy
#自定义包路径
parent=com.hanfengyi.system

#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///hrm-system
jdbc.user=root
jdbc.pwd=112334
  1. 在resources下创建一个templates文件夹导入query、controller的模板,对模板简单修改,保证包名的正确

模板的文件名:query.java.vm controller.java.vm

controller:

package ${package.Controller};

import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.itsource.hrm.query.${entity}Query;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
    * 保存和修改公用的
    * @param ${table.entityPath}  传递的实体
    * @return Ajaxresult转换结果
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
        try {
            if(${table.entityPath}.getId()!=null){
                ${table.entityPath}Service.updateById(${table.entityPath});
            }else{
                ${table.entityPath}Service.insert(${table.entityPath});
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败!"+e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            ${table.entityPath}Service.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败!"+e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public ${entity} get(@PathVariable("id")Long id)
    {
        return ${table.entityPath}Service.selectById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public List<${entity}> list(){

        return ${table.entityPath}Service.selectList(null);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public PageList<${entity}> json(@RequestBody ${entity}Query query)
    {
        Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
        page = ${table.entityPath}Service.selectPage(page);
        return new PageList<${entity}>(page.getTotal(),page.getRecords());
    }
}

query:

package cn.itsource.hrm.query;


/**
 *
 * @author ${author}
 * @since ${date}
 */
public class ${table.entityName}Query extends BaseQuery{
}

PageList

package com.hanfengyi.hrm.utils;

import java.util.ArrayList;
import java.util.List;
//分页对象:easyui只需两个属性,total(总数),datas(分页数据)就能实现分页
public class PageList {
    private long total;
    private List rows = new ArrayList<>();

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }

    @Override
    public String toString() {
        return "PageList{" +
                "total=" + total +
                ", rows=" + rows +
                '}';
    }

    //提供有参构造方法,方便测试
    public PageList(long total, List rows) {
        this.total = total;
        this.rows = rows;
    }
    //除了有参构造方法,还需要提供一个无参构造方法
    public PageList() {
    }
}

  1. 创建启动类用来生成代码
package com.hanfengyi;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.*;

/**
 * Created by CDHong on 2018/4/6.
 */
//代码生成的主类
public class GenteratorCode {

    //运行main方法就可以生成代码了
    public static void main(String[] args) throws InterruptedException {
        //用来获取Mybatis-Plus.properties文件的配置信息
        //不要加后缀
        final ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-course-config");
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(rb.getString("OutputDir"));
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 开启 activeRecord 模式
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
        gc.setAuthor(rb.getString("author"));
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert());
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(rb.getString("jdbc.user"));
        dsc.setPassword(rb.getString("jdbc.pwd"));
        dsc.setUrl(rb.getString("jdbc.url"));
        mpg.setDataSource(dsc);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[]{"t_course_type"}); // 需要生成的表 :
        mpg.setStrategy(strategy);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(rb.getString("parent")); //基本包 com.hanfengyi.course
        pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setEntity("domain");
        pc.setMapper("mapper");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map map = new HashMap();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
                this.setMap(map);
            }
        };

        List focList = new ArrayList();


        // 调整 controller 生成目录演示
        focList.add(new FileOutConfig("/templates/controller.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //controller输出完整路径
                return rb.getString("OutputDir")+ "/com/hanfengyi/course/web/controller/" + tableInfo.getEntityName() + "Controller.java";
            }
        });
        // 调整 query 生成目录演示
        focList.add(new FileOutConfig("/templates/query.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //query输出完整路径
                return rb.getString("OutputDirBase")+ "/com/hanfengyi/course/query/" + tableInfo.getEntityName() + "Query.java";
            }
        });
        // 调整 domain 生成目录演示 , 你的domain到底要输出到哪儿????,你的domain怎么输出
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                //domain输出完整路径
                return rb.getString("OutputDirBase")+ "/com/hanfengyi/course/domain/" + tableInfo.getEntityName() + ".java";
            }
        });

        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return rb.getString("OutputDirXml")+ "/com/hanfengyi/course/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
        TemplateConfig tc = new TemplateConfig();
        tc.setService("/templates/service.java.vm");
        tc.setServiceImpl("/templates/serviceImpl.java.vm");
        tc.setEntity(null);
        tc.setMapper("/templates/mapper.java.vm");
        tc.setController(null);
        tc.setXml(null);
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
        mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();
    }

}

BaseQuery

package com.hanfengyi.hrm.query;


/**
 * 基础查询对象
 */
public class BaseQuery {
    //关键字
    private String keyword;
    //有公共属性-分页
    private Integer page = 1; //当前页
    private Integer rows = 10; //每页显示多少条

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }
}

AjaxResult

package com.hanfengyi.hrm.utils;

//Ajax请求响应对象的类
public class AjaxResult {
    private boolean success = true;
    private String message = "操作成功!";


    //返回到前台对象
    private Object resultObj;

    public boolean isSuccess() {
        return success;
    }

    public AjaxResult setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public AjaxResult setMessage(String message) {
        this.message = message;
        return this;
    }

    public Object getResultObj() {
        return resultObj;
    }

    public AjaxResult setResultObj(Object resultObj) {
        this.resultObj = resultObj;
        return this;
    }

    //AjaxResult.me()成功
    //AjaxResult.me().setMessage()成功
    //AjaxResult.me().setSuccess(false),setMessage("失败");
    public  static AjaxResult me(){
        return new AjaxResult();
    }



    /*
    //成功
    public AjaxResult() {
    }

    //失败并且有提示
    public AjaxResult(String message) {
        this.success = false;
        this.message = message;
    }*/
}

  1. 在hrm-systemmanage-service-2010模块中导入mybatis-plus依赖
            
                com.alibaba
                druid
                1.1.11
            
            
                com.baomidou
                mybatis-plus-boot-starter
                2.2.0
            
             
            mysql
            mysql-connector-java
            
  1. 对报红的代码重新在pom中导入依赖!主配置类使用注解扫描mapper,开启事务管理,使用分页插件

    @SpringBootApplication
    @MapperScan(value = "com.hanfengyi.system.mapper") //扫描包
    @EnableTransactionManagement //开启事务支持
    public class SystemServer2010 {
        public static void main(String[] args) {
            SpringApplication.run(SystemServer2010.class );
        }
        /**
         * 分页插件
         */
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            return new PaginationInterceptor();
        }
    }
    

  2. 在resources下创建配置文件,集成datasource数据源、mybatis-plus

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1010/eureka/ #注册中心服务端的注册地址
  instance:
    prefer-ip-address: true #使用ip进行注册
    instance-id: system-server:2010  #服务注册到注册中心的id
server:
  port: 2010
#应用的名字
spring:
  application:
    name: system-server
  #集成DataSource
  datasource:
    username: root
    password: 112334
    url: jdbc:mysql:///hrm-system
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

#集成Mybatis-plus
mybatis-plus:
  mapper-locations: classpath:com/hanfengyi/system/mapper/*Mapper.xml
  1. 创建一个单独存放配置文件的文件夹,用来从git远程拉取配置文件,把zuul和systemmanage注册到注册中心!
  2. 简单测试 启动服务访问http://localhost:2010/system/systemdictionary/list 如果能够拿到数据,表示集成成功!

五:完成hrm-course-service-2020的搭建

与hrm-systemmanage-service-2010的搭建是一样的

六:接口文档Swagger的集成

①:导入依赖

            
                io.springfox
                springfox-swagger2
                2.9.2
            
            
                io.springfox
                springfox-swagger-ui
                2.9.2
            

②:创建启动类

@Configuration
@EnableSwagger2
public class Swagger2 {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //对外暴露服务的包,以controller的方式暴露,所以就是controller的包.
                .apis(RequestHandlerSelectors.basePackage("com.hanfengyi.system.web.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("平台服务api")
                .description("平台服务接口文档说明")
                .contact(new Contact("test", "", "[email protected]"))
                .version("1.0")
                .build();
    }

}

③:测试

启动服务,访问:http://localhost:2010/swagger-ui.html

七:zuul网关整合Swagger

在zuul模块中导入依赖

        
            io.springfox
            springfox-swagger2
        
        
            io.springfox
            springfox-swagger-ui
        

创建两个配置类

SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("人力资源平台")
                .description("人力资源平台接口文档说明")
                .termsOfServiceUrl("http://localhost:1020")
                .contact(new Contact("test", "", "[email protected]"))
                .version("1.0")
                .build();
    }
}

DocumentationConfig

resources.add(swaggerResource(服务名字,服务访问路径,版本号);

@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
    @Override
    public List get() {
        List resources = new ArrayList<>();
        resources.add(swaggerResource("系统管理", "/system/v2/api-docs", "2.0"));
        resources.add(swaggerResource("课程管理", "/course/v2/api-docs", "2.0"));
        return resources;

    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

你可能感兴趣的:(HRM微服务项目day-01)