SpringBoot + MyBatis-Plus+DM8 +Elasic-job 通用代码框架
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot + MyBatis-Plus+DM8 +Elasic-job 通用代码框架相关的知识,希望对你有一定的参考价值。
目录
1、基础技术框架
技术名称 | 版本 |
SpringBoot | 2.1.9.RELEASE |
MyBatis-plus | 3.3.1 |
DM8 | 18 |
lombok | 1.18.10 |
hutool-all | 5.5.2 |
druid | 1.2.3 |
swagger3 | 3.0.0 |
aop | 1.9.4 |
fastjson | 1.2.47 |
elastic-job | 2.1.5 |
2、完整pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.building</groupId>
<artifactId>digipower-building</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 集成Mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- 集成DM8 驱动包 -->
<dependency>
<groupId>dm.jdbc</groupId>
<artifactId>DmJdbcDriver18</artifactId>
<version>18</version>
</dependency>
<!--集成lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 集成guava 工具包 -->
<!-- 集成hutool-all 工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.2</version>
</dependency>
<!--druid 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<!-- swagger3 接口文档生成器 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
<exclusions>
<exclusion>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- 集成SpringAop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 集成Alibaba fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- 集成elastic-job 分布式定时任务 -->
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.5</version>
</dependency>
</dependencies>
<build>
<finalName>gcxt-building</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3、初始化脚本
CREATE TABLE "SYSDBA"."SYS_BUILDING_INFO"
(
"SID" VARCHAR(50) NOT NULL,
"DISTRICT" VARCHAR(50),
"SUB_DISTRICT" VARCHAR(50),
"BUSINESS_ID" VARCHAR(50),
"BASIC_ID" VARCHAR(50),
"TYPE" VARCHAR(50),
"NAME" VARCHAR(50),
"LOCATION" VARCHAR(500),
"ATTRIBUTES" VARCHAR(500),
CLUSTER PRIMARY KEY("SID")) STORAGE(ON "MAIN", CLUSTERBTR) ;
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."ATTRIBUTES" IS '楼栋详情信息';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."BASIC_ID" IS '楼栋编码';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."BUSINESS_ID" IS '楼栋业务ID';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."DISTRICT" IS '行政区域';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."LOCATION" IS '楼栋地理位置';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."NAME" IS '楼栋名称';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."SID" IS '主键';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."SUB_DISTRICT" IS '区域街道';
COMMENT ON COLUMN "SYSDBA"."SYS_BUILDING_INFO"."TYPE" IS '业务类型';
4、项目结构截图:
5、业务模块说明
com.digipower.entity = 实体对象定义
com.digipower.mapper= 接口映射
com.digipower.service= 服务定义
com.digipower.service.impl= 服务实列化
com.digipower.controller=业务控制层
package com.digipower.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@TableName("sys_building_info")
@EqualsAndHashCode(callSuper = false)
@Builder
@SuppressWarnings("serial")
public class BuildingInfo extends Model<BuildingInfo> implements Serializable
private String sid;
private String district;
private String subDistrict;
private String businessId;
private String basicId;
private String type;
private String name;
private String location;
private String attributes;
package com.digipower.mapper;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.digipower.entity.BuildingInfo;
@Mapper
public interface BuildingInfoMapper extends BaseMapper<BuildingInfo>
package com.digipower.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.digipower.entity.BuildingInfo;
public interface BuildingInfoService extends IService<BuildingInfo>
/**
* 查询列表数据
*
* @param building 楼栋信息
* @param current 当前页
* @param size 每页显示条数
* @return
*/
public Page<BuildingInfo> listData(BuildingInfo building, long current, long size);
package com.digipower.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.digipower.entity.BuildingInfo;
import com.digipower.mapper.BuildingInfoMapper;
import com.digipower.service.BuildingInfoService;
import cn.hutool.core.util.StrUtil;
@Service
public class BuildingInfoServiceImpl extends ServiceImpl<BuildingInfoMapper, BuildingInfo> implements BuildingInfoService
@Override
public Page<BuildingInfo> listData(BuildingInfo building, long current, long size)
// TODO Auto-generated method stub
QueryWrapper<BuildingInfo> queryWrapper = new QueryWrapper<>();
if (null != building.getSid())
queryWrapper.eq("sid", building.getSid());
//district
if (StrUtil.isNotBlank(building.getDistrict()))
queryWrapper.eq("district", building.getDistrict());
//
if (StrUtil.isNotBlank(building.getSubDistrict()))
queryWrapper.eq("sub_district", building.getSubDistrict());
if (StrUtil.isNotBlank(building.getName()))
queryWrapper.like("name", building.getName());
return baseMapper.selectPage(new Page<>(current, size), queryWrapper);
package com.digipower.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.digipower.common.Response;
import com.digipower.entity.BuildingInfo;
import com.digipower.service.BuildingInfoService;
@Controller
@RequestMapping(value = "building")
public class BuildingInfoController
@Autowired
private BuildingInfoService buildingInfoService;
@RequestMapping(value = "listData")
@ResponseBody
public Response<Page<BuildingInfo>> listData(BuildingInfo auth, @RequestParam(name = "page") long current,
@RequestParam(name = "limit") long size)
Page<BuildingInfo> page = buildingInfoService.listData(auth, current, size);
return Response.success(page);
6、通用模块说明
com.digipower.common= 响应封装和UUID生成工具
com.digipower.common.elastic.job= 定时任务框架封装
package com.digipower.common;
import java.io.PrintWriter;
import javax.servlet.ServletResponse;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Response<T>
/**
* 响应码
*/
private int code;
/**
* 响应消息体
*/
private String msg;
/**
* 响应数据
*/
private T data;
/**
* 失败响应
*
* @param code 响应码
* @param msg 响应消息体
* @param data 响应数据
* @return
*/
public static <T> Response<T> error(int code, String msg, T data)
return new Response<T>(code, msg, data);
/**
* 失败响应
*
* @param msg 响应消息体
* @return
*/
public static <T> Response<T> error(String msg)
return new Response<T>(500, msg, null);
/**
* 成功响应
*
* @param data 响应数据
* @return
*/
public static <T> Response<T> success(T data)
return new Response<T>(200, null, data);
/**
* 成功响应
*
* @param msg 响应消息体
* @return
*/
public static <T> Response<T> success(String msg)
return new Response<T>(200, msg, null);
/**
* 成功响应
*
* @param msg 响应消息体
* @param data 响应数据
* @return
*/
public static <T> Response<T> success(String msg, T data)
return new Response<T>(200, msg, data);
/**
* Response输出Json格式
*
* @param response
* @param data 返回数据
*/
public static void responseJson(ServletResponse response, Object data)
PrintWriter out = null;
try
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
out = response.getWriter();
out.println(JSONUtil.toJsonStr(data));
out.flush();
catch (Exception e)
finally
if (out != null)
out.close();
package com.digipower.common;
import java.util.UUID;
/**
* UUID 工具类
* @author zzg
*
*/
public class UUIDUtils
public static String getUUID()
return UUID.randomUUID().toString().replace("-", "");
package com.digipower.common.elastic.job;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
@Configuration
public class ElasticRegCenterConfig
// zookeeper地址信息
@Value("$zookeeper.serverLists")
private String serverList;
// 命名空间
@Value("$zookeeper.namespace")
private String namespace;
@Value("$zookeeper.digest")
private String digest;
@Bean(initMethod = "init")
public ZookeeperRegistryCenter regCenter()
ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverList, namespace);
if(StringUtils.isNotEmpty(digest))
zookeeperConfiguration.setDigest(digest);
return new ZookeeperRegistryCenter(zookeeperConfiguration);
package com.digipower.common.elastic.job;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
/**
* 分布式任务实例化
* @author zzg
*
*/
@Configuration
public class ElasticSchedulerInit
// 日志记录
public static final Logger log = LoggerFactory.getLogger(ElasticSchedulerInit.class);
@Autowired
private ZookeeperRegistryCenter regCenter;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void startSimpleJob()
applicationContext.getBeansWithAnnotation(ElasticSchedulerParam.class).forEach((className, obj) ->
ElasticSchedulerParam config = obj.getClass().getAnnotation(ElasticSchedulerParam.class);
String cron = StringUtils.defaultIfBlank(config.cron(), config.value());
int shardingTotalCount = config.shardingTotalCount();
String shardingItemParameters = config.shardingItemParameters();
MyElasticJobListener elasticJobListener = new MyElasticJobListener();
SimpleJob simpleJob = (SimpleJob) obj;
new SpringJobScheduler(simpleJob, regCenter,
getLiteJobConfiguration(simpleJob.getClass(), cron, shardingTotalCount, shardingItemParameters),
elasticJobListener).init();
);
// 私有方法
private LiteJobConfiguration getLiteJobConfiguration(final Class<? extends SimpleJob> jobClass, final String cron,
final int shardingTotalCount, final String shardingItemParameters)
return LiteJobConfiguration
.newBuilder(
new SimpleJobConfiguration(
JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount)
.shardingItemParameters(shardingItemParameters).build(),
jobClass.getCanonicalName()))
.overwrite(true).build();
package com.digipower.common.elastic.job;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* 分布式定时任务注解
*
* @author zzg
*
*/
@Target( ElementType.TYPE )
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface ElasticSchedulerParam
@AliasFor("value")
String cron() default "";
@AliasFor("cron")
String value() default "";
int shardingTotalCount() default 1;
String shardingItemParameters() default "0=0";
package com.digipower.common.elastic.job;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.ElasticJobListener;
/**
* 自定义ElasticJob 定时器
* @author zzg
*
*/
public class MyElasticJobListener implements ElasticJobListener
private static final Logger logger = LoggerFactory.getLogger(MyElasticJobListener.class);
/**
* 长日期格式
*/
public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private long beginTime = 0;
@Override
public void beforeJobExecuted(ShardingContexts shardingContexts)
beginTime = System.currentTimeMillis();
logger.info("===> JOB BEGIN TIME: <===", shardingContexts.getJobName(), beginTime);
@Override
public void afterJobExecuted(ShardingContexts shardingContexts)
long endTime = System.currentTimeMillis();
logger.info("===> JOB END TIME: ,TOTAL CAST: <===", shardingContexts.getJobName(), endTime,
endTime - beginTime);
/**
* 将长整型数字转换为日期格式的字符串
*
* @param time
* @param format
* @return
*/
public static String convert2String(long time, String format)
if (time > 0l)
if (StringUtils.isBlank(format))
format = TIME_FORMAT;
SimpleDateFormat sf = new SimpleDateFormat(format);
Date date = new Date(time);
return sf.format(date);
return "";
7、系统初始化配置
com.digipower.config = 系统配置化
package com.digipower.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisPlusConfig
/**
* 注入分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor()
return new PaginationInterceptor();
8、系统入口
package com.digipower;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* @ClassName: BuildingApplication
* @Description: 程序启动入口
*/
@SpringBootApplication
public class BuildingApplication
public static void main(String[] args)
// TODO Auto-generated method stub
SpringApplication.run(BuildingApplication.class, args);
9、配置参数和日志
application.properties
# \\u6307\\u5B9A\\u670D\\u52A1\\u7AEF\\u53E3
server.port=5088
# \\u6307\\u5B9A\\u65E5\\u5FD7\\u6587\\u4EF6\\u914D\\u7F6E
logging.config=classpath:logback.xml
# DM setting
spring.datasource.url=jdbc:dm://127.0.0.1:5256/SYSDBA
spring.datasource.username=SYSDBA
spring.datasource.password=SYSDBA
spring.datasource.driver-class-name=dm.jdbc.driver.DmDriver
# druid \\u6570\\u636E\\u5E93\\u8FDE\\u63A5\\u6C60\\u914D\\u7F6E
# \\u4E0B\\u9762\\u4E3A\\u8FDE\\u63A5\\u6C60\\u7684\\u8865\\u5145\\u8BBE\\u7F6E\\uFF0C\\u5E94\\u7528\\u5230\\u4E0A\\u9762\\u6240\\u6709\\u6570\\u636E\\u6E90\\u4E2D
# \\u521D\\u59CB\\u5316\\u5927\\u5C0F\\uFF0C\\u6700\\u5C0F\\uFF0C\\u6700\\u5927
spring.datasource.druid.initialSize=10
spring.datasource.druid.minIdle=10
spring.datasource.druid.maxActive=200
# \\u914D\\u7F6E\\u83B7\\u53D6\\u8FDE\\u63A5\\u7B49\\u5F85\\u8D85\\u65F6\\u7684\\u65F6\\u95F4
spring.datasource.druid.maxWait=6000
# \\u914D\\u7F6E\\u95F4\\u9694\\u591A\\u4E45\\u624D\\u8FDB\\u884C\\u4E00\\u6B21\\u68C0\\u6D4B\\uFF0C\\u68C0\\u6D4B\\u9700\\u8981\\u5173\\u95ED\\u7684\\u7A7A\\u95F2\\u8FDE\\u63A5\\uFF0C\\u5355\\u4F4D\\u662F\\u6BEB\\u79D2
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# \\u914D\\u7F6E\\u4E00\\u4E2A\\u8FDE\\u63A5\\u5728\\u6C60\\u4E2D\\u6700\\u5C0F\\u751F\\u5B58\\u7684\\u65F6\\u95F4\\uFF0C\\u5355\\u4F4D\\u662F\\u6BEB\\u79D2
spring.datasource.druid.minEvictableIdleTimeMillis=100000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
# \\u6253\\u5F00PSCache\\uFF0C\\u5E76\\u4E14\\u6307\\u5B9A\\u6BCF\\u4E2A\\u8FDE\\u63A5\\u4E0APSCache\\u7684\\u5927\\u5C0F
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# \\u914D\\u7F6E\\u76D1\\u63A7\\u7EDF\\u8BA1\\u62E6\\u622A\\u7684filters\\uFF0C\\u53BB\\u6389\\u540E\\u76D1\\u63A7\\u754C\\u9762sql\\u65E0\\u6CD5\\u7EDF\\u8BA1\\uFF0C'wall'\\u7528\\u4E8E\\u9632\\u706B\\u5899
spring.datasource.druid.filters=stat,slf4j
# \\u901A\\u8FC7connectProperties\\u5C5E\\u6027\\u6765\\u6253\\u5F00mergeSql\\u529F\\u80FD\\uFF1B\\u6162SQL\\u8BB0\\u5F55
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# \\u914D\\u7F6EMyBatis-plus
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.global-config.db-config.id-type=AUTO
# elastic-job\\u5B9A\\u65F6\\u4EFB\\u52A1\\u914D\\u7F6E\\u53C2\\u6570
zookeeper.serverLists=127.0.0.1:2181
zookeeper.namespace=building_elasticjob
zookeeper.digest=
# setting
building.url=http://127.0.0.1/gw/BUILDING/shenzhenS/LOU
building.key=KZZfAHBau2Xme6irarMoD1ohume1E7DoGzQdGeJCE1GgnPIOmvz2U94Cf9vqM72jnjKgoyHmppBgwwLi6wZED0a/RtzEZ7grD04kOLFcLAE=
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- 从高到地低 OFF 、 FATAL 、 ERROR 、 WARN 、 INFO 、 DEBUG 、 TRACE 、 ALL -->
<!-- 日志输出规则 根据当前ROOT 级别,日志输出时,级别高于root默认的级别时 会输出 -->
<!-- 以下 每个配置的 filter 是过滤掉输出文件里面,会出现高级别文件,依然出现低级别的日志信息,通过filter 过滤只记录本级别的日志-->
<!-- 属性描述 scan:性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,
默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 定义日志文件 输入位置 -->
<property name="log_dir" value="/logs/building" />
<!-- 日志最大的历史 30天 -->
<property name="maxHistory" value="30"/>
<!-- ConsoleAppender 控制台输出日志 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- 对日志进行格式化 -->
<encoder>
<pattern>%dyyyy-MM-dd HH:mm:ss [%thread] %-5level %logger -%msg%n</pattern>
</encoder>
</appender>
<!-- ERROR级别日志 -->
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 RollingFileAppender-->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只记录WARN级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<!-- 最常用的滚动策略,它根据时间来制定滚动策略.既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志输出位置 可相对、和绝对路径 -->
<fileNamePattern>$log_dir/%dyyyy-MM-dd/error.log</fileNamePattern>
<!-- 可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件假设设置每个月滚动,且<maxHistory>是6,
则只保存最近6个月的文件,删除之前的旧文件。注意,删除旧文件是,那些为了归档而创建的目录也会被删除-->
<maxHistory>$maxHistory</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%dyyyy-MM-dd HH:mm:ss.SSS [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- WARN级别日志 appender -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只记录WARN级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>WARN</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>$log_dir/%dyyyy-MM-dd/warn.log
</fileNamePattern>
<maxHistory>$maxHistory</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%dyyyy-MM-dd HH:mm:ss.SSS [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- INFO级别日志 appender -->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,只记录INFO级别的日志 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>$log_dir/%dyyyy-MM-dd/info.log
</fileNamePattern>
<maxHistory>$maxHistory</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%dyyyy-MM-dd HH:mm:ss.SSS [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- DEBUG级别日志 appender -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>DEBUG</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>$log_dir/%dyyyy-MM-dd/debug.log
</fileNamePattern>
<maxHistory>$maxHistory</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%dyyyy-MM-dd HH:mm:ss.SSS [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<logger name="org.springframework.web"/>
<logger name="com.digipower" />
<!-- root级别 DEBUG -->
<root level="INFO">
<!-- 控制台输出 -->
<appender-ref ref="STDOUT" />
<!-- 文件输出 -->
<appender-ref ref="ERROR" />
<appender-ref ref="INFO" />
<appender-ref ref="WARN" />
<appender-ref ref="DEBUG" />
</root>
</configuration>
10、Mapper 配置文件
BuildingInfoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.digipower.mapper.BuildingInfoMapper">
</mapper>
11、定时任务实列化
com.digipower.job = 定时任务实列化对象
package com.digipower.job;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.digipower.common.UUIDUtils;
import com.digipower.common.elastic.job.ElasticSchedulerParam;
import com.digipower.entity.BuildingInfo;
import com.digipower.service.BuildingInfoService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
@ElasticSchedulerParam(cron = "* */2 * * * ?", shardingTotalCount = 1, shardingItemParameters = "0=Core")
@Component
public class BuildingJobDemo implements SimpleJob
private static final Logger log = LoggerFactory.getLogger(BuildingJobDemo.class);
@Value("$building.url")
private String url;
@Value("$building.key")
private String key;
@Autowired
private BuildingInfoService buildingInfoService;
@Override
public void execute(ShardingContext shardingContext)
// TODO Auto-generated method stub
int num = buildingInfoService.count();
System.out.println("楼栋数据总数:" + num);
// 存在记录不执行插入操作
// hutool 发起网络请求
Map<String, Object> map = new HashMap<>();// 存放参数
map.put("pageNum", 1);
map.put("pageSize", 500);
map.put("district", "龙岗区");
map.put("subDistrict", "坂田街道");
map.put("operation", "list");
HashMap<String, String> headers = new HashMap<>();// 存放请求头,可以存放多个请求头
headers.put("Content-Type", "application/json");
headers.put("szvsud-license-key", key);
// 发送POST请求并接收响应数据
String result = HttpUtil.createPost(url).addHeaders(headers).form(map).execute().body();
if (StrUtil.isNotEmpty(result))
analyzeJSON(result);
public void analyzeJSON(String str)
List<BuildingInfo> list = new ArrayList<BuildingInfo>();
System.out.println("后台响应:" + str);
JSONObject json = new JSONObject(str);
boolean success = json.getBool("success");
System.out.println("楼栋数据请求是否成功:" + success);
if (success)
JSONArray array = json.getJSONArray("dataList");
for (int i = 0; i < array.size(); i++)
JSONObject jsonObject = array.getJSONObject(i);
BuildingInfo obj = BuildingInfo.builder().attributes(jsonObject.getJSONObject("attributes").toString())
.basicId(jsonObject.getStr("basicId")).businessId(jsonObject.getStr("id")).district("龙岗区")
.location(jsonObject.getJSONObject("location").toString()).name(jsonObject.getStr("name"))
.sid(UUIDUtils.getUUID()).subDistrict("坂田街道").type(jsonObject.getStr("type")).build();
list.add(obj);
if (CollectionUtil.isNotEmpty(list))
buildingInfoService.saveBatch(list);
12、程序效果截图:
以上是关于SpringBoot + MyBatis-Plus+DM8 +Elasic-job 通用代码框架的主要内容,如果未能解决你的问题,请参考以下文章
如何整合 springboot + mybatis-plus(系列一)
SpringBoot使用·下篇(SpringBoot集成MyBatis+日志打印+MyBatis-plus)