zhongdaoyi@wondertek.com.cn

init2

<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>${project.version}</id>
<formats>
<format>dir</format>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${build.directory}</baseDirectory>
<fileSets>
<!-- <fileSet>-->
<!-- <directory>conf/</directory>-->
<!-- <outputDirectory>${project.artifactId}/conf</outputDirectory>-->
<!-- </fileSet>-->
<fileSet>
<directory>db/</directory>
<outputDirectory>${project.artifactId}/db</outputDirectory>
</fileSet>
<fileSet>
<directory>${build.directory}</directory>
<includes>
<include>*.jar</include>
</includes>
<excludes>
<exclude>*sources.jar</exclude>
</excludes>
<outputDirectory>${project.artifactId}/lib</outputDirectory>
</fileSet>
<fileSet>
<directory>bin/</directory>
<outputDirectory>${project.artifactId}/bin</outputDirectory>
<fileMode>754</fileMode>
<lineEnding>unix</lineEnding>
</fileSet>
</fileSets>
</assembly>
... ...
#!/bin/bash
source /etc/profile
BASE_HOME=/opt
APP_NAME=crp-operation
APP_HOME=${BASE_HOME}/${APP_NAME}
APP_VERSION=1.0.0
SERVICE_NAME=${APP_NAME}
LOG_HOME=${APP_HOME}/logs
LOG_PATH=${LOG_HOME}/${APP_NAME}
ENV_LIST=("default" "dev" "test" "prod")
SERVICE_LIB=${APP_HOME}/lib
SERVICE_CONF=${APP_HOME}/conf
SERVICE_RESOURCES=${APP_HOME}/resources
if [[ -n "$2" ]]; then
PROJECT_ENV=$2
else
PROJECT_ENV="dev"
fi
safemkdir(){
if [[ ! -d $1 ]] ; then
mkdir -p $1
fi
}
# Production config
if [[ "$PROJECT_ENV" == "prod" ]]; then
JAVA_OPTIONS="-server -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$LOG_PATH -Xms128M -Xmx256M -Xmn512M -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=256M -XX:+DisableExplicitGC -XX:SurvivorRatio=8 -XX:LargePageSizeInBytes=128M -XX:SoftRefLRUPolicyMSPerMB=0 "
else
JAVA_OPTIONS="-server -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$LOG_PATH -Xms128M -Xmx256M -Xmn128M -XX:MetaspaceSize=128M -XX:MaxMetaspaceSize=256M -XX:+DisableExplicitGC -XX:SurvivorRatio=8 -XX:LargePageSizeInBytes=128M -XX:SoftRefLRUPolicyMSPerMB=0"
fi
if [[ "$PROJECT_ENV" == "dev" || "$PROJECT_ENV" == "test" ]]; then
JAVA_OPTIONS="-Xdebug -Xrunjdwp:transport=dt_socket,address=$REMOTE_PORT,server=y,suspend=n $JAVA_OPTIONS"
fi
JAVA_OPTIONS="-XX:ErrorFile=$LOG_PATH/hs_err_pid%p.log $JAVA_OPTIONS -Dspring.cloud.inetutils.ignored-interfaces=lo.* -Dspring.config.additional-location=$SERVICE_CONF/ -Dspring.profiles.active=$PROJECT_ENV -Dapp.name=$APP_NAME -Dlog.home=$LOG_HOME -Denv=$PROJECT_ENV -Djava.security.egd=file:/dev/./urandom"
export CLASSPATH=${CLASSPATH}:${SERVICE_CONF}:${SERVICE_RESOURCES}
export JAVA_OPTIONS
export PID_FILE=${APP_HOME}/.pid/${APP_NAME}.pid
dateFormat=$(date '+%Y-%m-%d')
safemkdir ${APP_HOME}/.pid/
safemkdir ${LOG_PATH}/
ACCESS_LOG=${LOG_PATH}/${dateFormat}.info.log
ERROR_LOG=${LOG_PATH}/${dateFormat}.error.log
hint="Usage: start "
hasEnv=0
checkEnvParam(){
for env_name in ${ENV_LIST[@]};do
if [[ "${env_name}" == "$1" ]] ; then
hasEnv=1
fi
done
}
getUsageHint(){
for env_name in ${ENV_LIST[@]};do
hint=${hint}${env_name}" or "
done
hint=${hint}"|stop|log|error"
}
checkEnvParam $2
getUsageHint
started="#################################################################################\n
Application [${APP_NAME}] for environment [${PROJECT_ENV}] Started At $(date) \n
##################################################################################\n"
stopped="#################################################################################\n
Application [${APP_NAME}] Stopped At $(date) \n
##################################################################################\n"
if [[ "$1" == "start" ]]; then
if [[ "${hasEnv}" == 0 ]]; then
echo ${hint}
exit 0
fi
if [[ ! -f "$PID_FILE" ]]; then
echo -e ${started} | tee -a ${ACCESS_LOG}
nohup java ${JAVA_OPTIONS} ${SCOUNT_CONFIG} -jar ${APP_HOME}/lib/${APP_NAME}-${APP_VERSION}.jar 1>> ${ACCESS_LOG} 2>> ${ERROR_LOG} 2>&1 &echo $! > ${PID_FILE}
sleep 10
tail -n 300 ${ACCESS_LOG}
else
echo "$APP_NAME service already started, please stop first and try again"
fi
elif [[ "$1" == "stop" ]]; then
if [[ -f "$PID_FILE" ]]; then
echo -e ${stopped} | tee -a ${ACCESS_LOG}
cat ${PID_FILE} | xargs kill -9
rm ${PID_FILE}
echo "$APP_NAME stop : [OK]"
else
echo "$APP_NAME service not started yet, please start first and try again"
fi
elif [[ "$1" == "log" ]]
then if [[ "$2" == "error" ]]
then
tail -f ${ERROR_LOG}
else
tail -f ${ACCESS_LOG}
fi
elif [[ "$1" == "-v" ]]; then
echo ${APP_VERSION}
elif [[ "$1" == "status" ]]; then
pid=`cat ${PID_FILE}`
if [[ $? -eq 0 ]]; then
p_status=`ps -p ${pid}`
if [[ $? -eq 0 ]]; then
echo "Application [${APP_NAME}] is running, pid : ${pid}."
else
echo "Application [${APP_NAME}] is not running."
fi
else
echo "Application [${APP_NAME}] is not running."
fi
else
echo ${hint}
fi
... ...
... ... @@ -6,7 +6,14 @@
<groupId>com.wondertek</groupId>
<artifactId>crp-operation</artifactId>
<version>1.0-SNAPSHOT</version>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>17</maven.compiler.source>
... ... @@ -14,4 +21,156 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<!--常用库依赖-->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<!-- <version>1.2.3</version>-->
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
</dependency>
</dependencies>
<build>
<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>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>db</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
... ...
package com.wondertek;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@MapperScan({"com.wondertek.mapper"})
@SpringBootApplication(scanBasePackages = {"com.wondertek"})
public class CrpOperationApplication {
public static void main(String[] args) {
SpringApplication.run(CrpOperationApplication.class, args);
}
}
\ No newline at end of file
... ...
package com.wondertek;
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
\ No newline at end of file
package com.wondertek.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置
*/
@Slf4j
@Configuration
@ConditionalOnProperty(value = {"light-blog.cors.enable"}, matchIfMissing = true)
public class CorsConfig implements WebMvcConfigurer {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 允许所有域名进行跨域调用
config.addAllowedOriginPattern("*");
// 允许任何请求头
config.addAllowedHeader("*");
// 允许任何方法(POST、GET等)
config.addAllowedMethod("*");
// 允许携带凭证
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对所有接口都有效
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
... ...
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.wondertek.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis-plus配置
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
public class MybatisPlusConfig {
/**
* 配置分页等
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 乐观锁
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 防止全表更新与删除
mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return mybatisPlusInterceptor;
}
}
\ No newline at end of file
... ...
/**
* Copyright (c) 2018 人人开源 All rights reserved.
* <p>
* https://www.renren.io
* <p>
* 版权所有,侵权必究!
*/
package com.wondertek.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.wondertek.util.DateUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.TimeZone;
/**
* MVC配置
*
* @author Mark sunlightcs@gmail.com
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter());
converters.add(new AllEncompassingFormHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(jackson2HttpMessageConverter());
}
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = new ObjectMapper();
//日期格式转换
// 解决jackson2无法反序列化LocalDateTime的问题
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,
new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addDeserializer(LocalDateTime.class,
new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(javaTimeModule);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//Long类型转String类型
// SimpleModule simpleModule = new SimpleModule();
// simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
// simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
// mapper.registerModule(simpleModule);
converter.setObjectMapper(mapper);
return converter;
}
}
... ...
package com.wondertek.controller;
import com.wondertek.dto.CrpBackupMaterialDto;
import com.wondertek.service.CrpBackupMaterialService;
import com.wondertek.util.PageBean;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("bkMaterial")
public class CrpBackupMaterialController {
@Resource
private CrpBackupMaterialService crpBackupMaterialService;
@GetMapping("queryPage")
PageBean queryPage(CrpBackupMaterialDto crpBackupMaterialDto){
return crpBackupMaterialService.queryPage(crpBackupMaterialDto);
}
}
... ...
package com.wondertek.dto;
import lombok.Data;
@Data
public class CrpBackupMaterialDto {
/** 垫片名称 */
private String backupName ;
private Integer page=1;
private Integer size=10;
}
... ...
package com.wondertek.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 垫片素材表;
* @author : http://www.chiner.pro
* @date : 2025-7-18
*/
@Data
@TableName("crp_backup_material")
public class CrpBackupMaterial extends Model<CrpBackupMaterial> {
/** id */
@TableId
private Long id ;
/** 文件类型 */
private String fileType ;
/** 文件路径 */
private String filePath ;
/** 垫片名称 */
private String backupName ;
/** 创建人 */
private String createdBy ;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createdTime ;
}
\ No newline at end of file
... ...
package com.wondertek.enums;
/**
* 系统全局编码
* @Description -1-99, 避开HTTP状态码100-600
*/
public enum GlobalCodeEnum {
FALLBACK("-2", "JPA服务熔断"),
UNKNOW_ERROR("-1", "未知错误"),
SUCCESS("0", "成功"),
FAILURE("1", "失败"),
INVALID_PARAMS("2", "请求参数无效"),
UNSUPPORTED_URI("3", "未知URI"),
TOUCH_API_LIMIT("4", "接口调用次数已达到设定的上限"),
NO_AUTHORIZATION("6", "无访问权限"),
//持久层错误
DB_ERROR("20", "数据库异常"),
SOLR_ERROR("21", "搜索引擎异常"),
//消息中间件错误
MQ_ERROR("30", "消息中间件异常");
private String code;
private String msg;
private GlobalCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
... ...
package com.wondertek.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wondertek.entity.CrpBackupMaterial;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CrpBackupMaterialMapper extends BaseMapper<CrpBackupMaterial> {
}
... ...
package com.wondertek.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.wondertek.dto.CrpBackupMaterialDto;
import com.wondertek.entity.CrpBackupMaterial;
import com.wondertek.util.PageBean;
import com.wondertek.util.PageResult;
public interface CrpBackupMaterialService extends IService<CrpBackupMaterial> {
PageBean queryPage(CrpBackupMaterialDto crpBackupMaterialDto);
}
... ...
package com.wondertek.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.dto.CrpBackupMaterialDto;
import com.wondertek.entity.CrpBackupMaterial;
import com.wondertek.mapper.CrpBackupMaterialMapper;
import com.wondertek.service.CrpBackupMaterialService;
import com.wondertek.util.PageBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
@Service
public class CrpBackupMaterialServiceImpl extends ServiceImpl<CrpBackupMaterialMapper, CrpBackupMaterial> implements CrpBackupMaterialService {
@Resource
private CrpBackupMaterialMapper crpBackupMaterialMapper;
@Override
public PageBean queryPage(CrpBackupMaterialDto crpBackupMaterialDto) {
Integer page = crpBackupMaterialDto.getPage();
Integer size = crpBackupMaterialDto.getSize();
LambdaQueryWrapper<CrpBackupMaterial> queryWrapper = new LambdaQueryWrapper<>();
if(StringUtils.isNotBlank(crpBackupMaterialDto.getBackupName())){
queryWrapper.like(CrpBackupMaterial::getBackupName,crpBackupMaterialDto.getBackupName());
}
Page<CrpBackupMaterial> pageInfo = new Page<>(page, size);
IPage<CrpBackupMaterial> resultPage = crpBackupMaterialMapper.selectPage(pageInfo, queryWrapper);
return new PageBean(Integer.parseInt(String.valueOf(resultPage.getPages())),resultPage.getTotal(),resultPage.getRecords());
}
}
... ...
package com.wondertek.util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
/**
* @author w4178
*/
@Slf4j
public class DateUtil {
public static final String regex = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat sdf = new SimpleDateFormat(regex);
private static final ThreadLocal<Map<String, DateFormat>> dateFormatThreadLocal = new ThreadLocal();
public static LocalDateTime toLocalDateTime(Date date) {
if (date != null) {
// return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
// return date.toInstant().atOffset(ZoneOffset.of("+0")).toLocalDateTime();
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
return null;
}
public static Date asDate(LocalDateTime localDateTime){
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDateTime asLocalDateTime(Date date){
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public static String format(LocalDateTime date) {
try {
if (date != null) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
} catch (Exception e) {
log.error("date 日期格式化错误:" + e.getMessage());
}
return "";
}
public static String format(Date date, String patten) {
return getDateFormat(patten).format(date);
}
private static DateFormat getDateFormat(String pattern) {
if (pattern != null && pattern.trim().length() != 0) {
Map<String, DateFormat> dateFormatMap = (Map)dateFormatThreadLocal.get();
if (dateFormatMap != null && ((Map)dateFormatMap).containsKey(pattern)) {
return (DateFormat)((Map)dateFormatMap).get(pattern);
} else {
synchronized(dateFormatThreadLocal) {
if (dateFormatMap == null) {
dateFormatMap = new HashMap();
}
((Map)dateFormatMap).put(pattern, new SimpleDateFormat(pattern));
dateFormatThreadLocal.set(dateFormatMap);
}
return (DateFormat)((Map)dateFormatMap).get(pattern);
}
} else {
throw new IllegalArgumentException("pattern cannot be empty.");
}
}
public static String dateToString(Date d,String format)
{
return new SimpleDateFormat(format).format(d);
}
public static String dateToString(Date d)
{
return new SimpleDateFormat(regex).format(d);
}
public static Date stringToDate(String s,String format) throws ParseException
{
return new SimpleDateFormat(format).parse(s);
}
public static Date stringToDate(String s) throws ParseException
{
return new SimpleDateFormat(regex).parse(s);
}
public static String resolve(LocalDateTime localDateTime) {
try {
if (localDateTime != null) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
return df.format(localDateTime);
}
} catch (Exception e) {
log.error("date 日期格式化错误:" + e.getMessage());
}
return "";
}
public static Long getTime(LocalDateTime localDateTime) {
if (localDateTime != null) {
Date date = DateUtil.toDate(localDateTime);
return date.getTime();
}
return null;
}
public static Date toDate(LocalDateTime localDateTime) {
if (localDateTime != null) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
return Date.from(zdt.toInstant());
}
return null;
}
public static Date toDate(String content) {
if (!StringUtils.isEmpty(content) && !"null".equals(content)) {
Long time = getTime(content);
if (time != null) {
return new Date(time);
}
}
return null;
}
/**
* <p><b>Title:</b> listBetweenMinutes</p>
* <p><b>Description:</b> 得到时间范围内所有时间(按分钟算),开始时间不算</p>
*
* @param startTime
* @param endTime
* @param s 间隔多少分钟
* @return
* @author Zewei.Zhou
*/
public static List<LocalDateTime> listBetweenMinutes(LocalDateTime startTime, LocalDateTime endTime, int s) {
long between = ChronoUnit.MINUTES.between(startTime.withSecond(0).withNano(0),
endTime.withSecond(0).withNano(0));
Assert.state(between >= 0, "开始时间必须小于等于结束时间");
List<LocalDateTime> list = new ArrayList<>(Integer.parseInt(between + ""));
list.add(startTime);
for (int i = s; i < between; i = i + s) {
list.add(startTime.plusMinutes(i));
}
return list;
}
public static boolean checkBetweenDays(String startTime,String endTime,Long days){
try {
long between = ChronoUnit.DAYS.between(DateUtil.str2date(startTime).withSecond(0).withNano(0),
DateUtil.str2date(endTime).withSecond(0).withNano(0));
return between > days;
}catch (Exception ex){
return false;
}
}
public static Long getTimeMill(String timeStr) {
String defaultDateFormat = "yyyy-MM-dd HH:mm:ss";
timeStr = timeStr.trim();
boolean flag = isDate(timeStr, defaultDateFormat);
if (flag) {
LocalDateTime localDateTime = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(defaultDateFormat));
Date date = DateUtil.toDate(localDateTime);
return date.getTime();
}
return null;
}
/**
* 判断是否为合法的日期时间字符串
*
* @param dateStr 时间字符串
* @param rDateFormat 时间格式化模板
* @return boolean;符合为true,不符合为false
*/
public static boolean isDate(String dateStr, String rDateFormat) {
if (!StringUtils.isEmpty(dateStr)) {
SimpleDateFormat formatter = new SimpleDateFormat(rDateFormat);
formatter.setLenient(false);
try {
formatter.format(formatter.parse(dateStr));
} catch (Exception e) {
return false;
}
return true;
}
return false;
}
/**
* localDateTime装换为Date
*
* @param localDateTime localDateTime
* @return Date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zoneId).toInstant();
return Date.from(instant);
}
// 把时间转为字符串
public static String date2Str(LocalDateTime time, String format) {
try {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
return pattern.format(time);
} catch (Exception e) {
log.info("时间转换为字符串异常:" + e.getMessage());
}
return null;
}
// 把字符串转换为时间
public static LocalDateTime str2date(String timeStr, String format) {
try {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern(format);
return LocalDateTime.parse(timeStr, pattern);
} catch (Exception e) {
log.info("字符串转换为时间异常:" + e.getMessage());
}
return null;
}
// 把字符串转换为时间
public static LocalDateTime str2date(String timeStr) {
try {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern(regex);
return LocalDateTime.parse(timeStr, pattern);
} catch (Exception e) {
log.info("字符串转换为时间异常:" + e.getMessage());
}
return null;
}
public static boolean isInTimeInterval(LocalDateTime nowTime,LocalDateTime startTime,LocalDateTime endTime){
if (startTime ==null){
return true;
}
if (endTime ==null){
return true;
}
if (nowTime.isAfter(startTime) && nowTime.isBefore(endTime)){
return true;
}
return false;
}
public static String secToTime(int time) {
String timeStr;
int hour;
int minute;
int second;
if (time <= 0) {
return "00:00:00";
} else {
minute = time / 60;
if (minute < 60) {
second = time % 60;
timeStr = "00:" + unitFormat(minute) + ":" + unitFormat(second);
} else {
hour = minute / 60;
if (hour > 99) {
return "99:59:59";
}
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
}
}
return timeStr;
}
private static String unitFormat(int i) {
String retStr = null;
if (i >= 0 && i < 10) {
retStr = "0" + Integer.toString(i);
} else {
retStr = "" + i;
}
return retStr;
}
public static List<String> listBetweenDays(String startTime, String endTime) {
List<String> resultList = new ArrayList<>(16);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate startDate = LocalDate.parse(startTime, pattern);
LocalDate endDate = LocalDate.parse(endTime, pattern);
while (startDate.isBefore(endDate) || startDate.isEqual(endDate)) {
resultList.add(pattern.format(startDate));
startDate = startDate.plusDays(1);
}
return resultList;
}
public static Long getTime(String content) {
String regex = "yyyy-MM-dd HH:mm:ss";
if (isDate(content.trim(), regex)) {
try {
Date d = sdf.parse(content);
return d.getTime();
} catch (ParseException e) {
log.error("{},格式化异常:{}", regex, e.getMessage());
}
}
return null;
}
public static boolean compareStartEndTime(String startTime,String endTime){
boolean flag =true;
int compareTo = startTime.compareTo(endTime);
if(compareTo>0){
flag= false;
}
return flag;
}
public static boolean isDateVail(String date){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(regex);
boolean flag =true;
try {
LocalDateTime.parse(date, dtf);
}catch (Exception ex){
flag =false;
}
return false;
}
public static LocalDateTime toStartOfDay(LocalDateTime time) {
return time.withHour(0).withMinute(0).withSecond(0).withNano(0);
}
public static String[] getLastMonthFirstAndLastDay(){
LocalDateTime time = LocalDateTime.now().minusMonths(6L);
LocalDateTime dayStart = DateUtil.getDayStart(time);
String format = DateUtil.format(dayStart);
return new String[]{"",format};
}
public static String[] getLastMonthFirstAndLastDays(){
SimpleDateFormat sm = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
//上个月
cal.add(Calendar.MONTH, -3);
cal.set(Calendar.DAY_OF_MONTH,1);
String firstDay = sm.format(cal.getTime());
Calendar call = Calendar.getInstance();
//设置上个月最后一天
call.add(Calendar.MONTH, -2);
call.set(Calendar.DAY_OF_MONTH,0);
String lastDay = sm.format(call.getTime());
return new String[]{firstDay,lastDay};
}
private static LocalDateTime getDate(String beforeDate) throws Exception{
SimpleDateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Date rdate = readFormat.parse(beforeDate);
SimpleDateFormat writeFormat = new SimpleDateFormat(regex, Locale.US);
String format = writeFormat.format(rdate);
return asLocalDateTime(writeFormat.parse(format));
}
// 获取一天的开始时间,2017,7,22 00:00
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0).withMinute(0).withSecond(0).withNano(0);
}
// 获取一天的结束时间,2017,7,22 23:59:59.999999999
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23).withMinute(59).withSecond(59).withNano(999999999);
}
}
... ...
package com.wondertek.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.wondertek.enums.GlobalCodeEnum;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* 分页对象
*
* @param <T>
*/
@Data
@ToString
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageBean<T> extends ResultBean {
/**
* 总的页数
*/
private Integer totalPage;
/**
* 总记录数
*/
private Long totalCount;
/**
* 分页数据
*/
private List<T> result;
public PageBean() {}
public PageBean(String code, String msg) {
super(code, msg);
}
/**
*
* @param totalPage 总页数
* @param totalCount 总数
* @param result
*/
public <K> PageBean(Integer totalPage, Long totalCount, List<T> result) {
super(GlobalCodeEnum.SUCCESS.getCode(), GlobalCodeEnum.SUCCESS.getMsg());
this.totalPage = totalPage;
this.totalCount = totalCount;
this.result = result;
}
public static <T> PageBean<T> ok(Integer totalPage, Long totalCount, List<T> result){
return new PageBean<>(totalPage, totalCount, result);
}
public static <T> PageBean<T> empty() {
return new PageBean<>(0, 0L, new ArrayList<>());
}
}
... ...
package com.wondertek.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
/**
* 分页对象
*
* @param <T>
*/
@Data
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageDTO<T> {
/**
* 总的页数
*/
private Integer totalPage;
/**
* 总记录数
*/
private Long totalCount;
/**
* 分页数据
*/
private List<T> list;
public PageDTO() {}
/**
*
* @param totalPage 总页数
* @param totalCount 总数
* @param list
*/
public <K> PageDTO(Integer totalPage, Long totalCount, List<T> list) {
this.totalPage = totalPage;
this.totalCount = totalCount;
this.list = list;
}
public static <T> PageDTO<T> ok(Integer totalPage, Long totalCount, List<T> list){
return new PageDTO<>(totalPage, totalCount, list);
}
public static <T> PageDTO<T> empty() {
return new PageDTO<>(0, 0L, new ArrayList<>());
}
}
... ...
package com.wondertek.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.wondertek.enums.GlobalCodeEnum;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageResult<T> {
/**
* 信息代码
*/
private String code;
/**
* 信息说明
*/
private String msg;
/**
* 返回数据或jqgrid中的root
*/
private PageDTO result;
public <K> PageResult() {
}
public PageResult(String code, String msg) {
this.code = code;
this.msg = msg;
}
public PageResult(String code, String msg, PageDTO result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public static <T> PageResult<T> ok() {
return new PageResult<>(GlobalCodeEnum.SUCCESS.getCode(), GlobalCodeEnum.SUCCESS.getMsg());
}
public static <T> PageResult<T> ok(PageDTO result) {
return new PageResult<T>(GlobalCodeEnum.SUCCESS.getCode(), GlobalCodeEnum.SUCCESS.getMsg(), result);
}
public boolean isSuccess() {
return GlobalCodeEnum.SUCCESS.getCode().equals(this.code);
}
public static <T> PageResult<T> error() {
return new PageResult<T>(GlobalCodeEnum.FAILURE.getCode(), GlobalCodeEnum.FAILURE.getMsg());
}
public static <T> PageResult<T> error(String msg) {
return new PageResult<T>(GlobalCodeEnum.FAILURE.getCode(), msg);
}
public static <T> PageResult<T> error(String code, String msg) {
return new PageResult<T>(code, msg);
}
public static <K> PageResult<K> error(String code, String msg, PageDTO k) {
return new PageResult<K>(code, msg, k);
}
}
... ...
package com.wondertek.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.wondertek.enums.GlobalCodeEnum;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResultBean<T> {
/**
* 信息代码
*/
private String code;
/**
* 信息说明
*/
private String msg;
/**
* 返回数据或jqgrid中的root
*/
private T result;
public <K> ResultBean() {
}
public ResultBean(String code, String msg) {
this.code = code;
this.msg = msg;
}
public ResultBean(String code, String msg, T result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public static <T> ResultBean<T> ok() {
return new ResultBean<>(GlobalCodeEnum.SUCCESS.getCode(), GlobalCodeEnum.SUCCESS.getMsg());
}
public static <T> ResultBean<T> ok(T result) {
return new ResultBean<T>(GlobalCodeEnum.SUCCESS.getCode(), GlobalCodeEnum.SUCCESS.getMsg(), result);
}
public boolean isSuccess() {
return GlobalCodeEnum.SUCCESS.getCode().equals(this.code);
}
public static <T> ResultBean<T> error() {
return new ResultBean<T>(GlobalCodeEnum.FAILURE.getCode(), GlobalCodeEnum.FAILURE.getMsg());
}
public static <T> ResultBean<T> error(String msg) {
return new ResultBean<T>(GlobalCodeEnum.FAILURE.getCode(), msg);
}
public static <T> ResultBean<T> error(String code, String msg) {
return new ResultBean<T>(code, msg);
}
public static <K> ResultBean<K> error(String code, String msg, K k) {
return new ResultBean<K>(code, msg, k);
}
}
... ...
server:
port: 8150
tomcat:
threads:
max: 1000
min-spare: 30
uri-encoding: UTF-8
spring:
application:
name: crp-operation
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://192.168.1.41:3306/crp_cloud?characterEncoding=UTF-8&useSSL=false&useUnicode=true&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
##配置初始化大小、最小、最大
initial-size: 5
max-active: 100
min-idle: 5
#配置获取连接等待超时的时间
max-wait: 60000
##打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
validation-query: SELECT 1 FROM DUAL
validation-query-timeout: 60000
##这里建议配置为TRUE,防止取到的连接不可用
test-on-borrow: true
test-on-return: false
test-while-idle: true
##配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 100000
jackson:
date-format: yyy-MM-dd HH:mm:ss
time-zone: GMT+8
banner:
charset: UTF-8
location: classpath:banner.txt
servlet:
multipart:
location: /opt/upload/tmp
max-file-size: 10MB
max-request-size: 100MB
mybatis-plus:
mapper-locations: classpath*:/mapper/*Mapper.xml
typeAliasesPackage: com.wondertek.entity #开启类型别名,降低冗余的全限定类名书写
configuration:
mapUnderscoreToCamelCase: true #开启自动驼峰命名规则(camel case)映射
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 配置sql打印日志
global-config:
db-config:
logic-not-delete-value: 1
logic-delete-value: 0
crp:
log:
open_console: true
... ...
spring:
profiles:
active: dev
... ...
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false" scan="false">
<springProperty scope="context" name="log_level" source="blog.log.level" defaultValue="INFO"/>
<springProperty scope="context" name="log_open_console" source="crp.log.open_console" defaultValue="false"/>
<springProperty scope="context" name="app_name" source="spring.application.name"
defaultValue="crp-operation"/>
<property name="log_path" value="/tools/logs"/>
<property name="log.pattern"
value="%d{yyyy-MM-dd HH:mm:ss.SSS}|%level|${PID:-}|%thread|${app_name:-}|%X{X-B3-TraceId:-}|%X{X-B3-SpanId:-}|%X{X-Span-Export:-}|%class.%method-%line|%msg%n"/>
<!-- Console log output -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- Log file debug output -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_path}/${app_name}/%d{yyyy-MM-dd}.info.log</fileNamePattern>
<maxHistory>90</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- Log file error output -->
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_path}/${app_name}/%d{yyyy-MM-dd}.error.log</fileNamePattern>
<maxHistory>90</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
</appender>
<!-- Feign log -->
<appender name="feignFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log_path}/${app_name}/%d{yyyy-MM-dd}.feign.log</fileNamePattern>
<maxHistory>90</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<logger name="feign" level="INFO" addtivity="false">
<appender-ref ref="feignFile"/>
</logger>
<!-- Level: FATAL 0 ERROR 3 WARN 4 INFO 6 DEBUG 7 -->
<root level="${log_level}">
<if condition='property("log_open_console").contains("true")'>
<then>
<appender-ref ref="console"/>
</then>
</if>
<appender-ref ref="file"/>
<appender-ref ref="error"/>
</root>
</configuration>
... ...