Commit c22743ae by yanchenglong

搭建项目

parents
File added
#gralde build
build
gradle
.gradle
classes
gradlew*
.gradle/
#idea
.idea/
*.iml
out
#java
*.class
#*.jar
*.war
*.ear
*.cfg
management_log/
management_app_log/
#elastic
data
#vscode
.classpath
.project
*/bin
*/.settings
.settings
*/.application.properties
application.properties
\ No newline at end of file
plugins {
id 'org.springframework.boot' version '2.1.5.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'com.maxrocky'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
//mavenCentral()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
//skip Test tasks
gradle.taskGraph.whenReady {
tasks.each { task ->
if (task.name.contains("test"))
{
task.enabled = false
}
}
}
ext {
swaggerVersion = '1.4.1.RELEASE'
orikaVersion = '1.5.1'
mybatisVersion = '1.3.1'
mySqlConnectorVersion = '5.0.8'
jacksonDatatypeVersion = '2.8.8'
jacksonDataFormatXmlVersion = '2.8.8'
pagehelperVersion = '4.1.0'
ossVersion = '2.8.3'
mockVersion = '2.0.8'
druidVersion = '1.1.5'
jnaVersion = '3.0.9'
fastJsonVersion = '1.2.35'
poiVersion='3.16'
EncodeVersion='4.11'
}
dependencies {
//依赖项目
compile project(':common')
//依赖项目
compile project(':redis')
//POI
compile ("org.apache.poi:poi:$poiVersion")
compile ("org.apache.poi:poi-ooxml:$poiVersion")
//分页插件
compile("com.github.pagehelper:pagehelper:${pagehelperVersion}")
//mysql
compile("mysql:mysql-connector-java:${mySqlConnectorVersion}")
//lombok
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
//配置Druid连接池
compile("com.alibaba:druid:${druidVersion}")
//重试机制--引入两个包
compile('org.springframework.retry:spring-retry')
//配置mapperFactory
compile("ma.glasnost.orika:orika-core:$orikaVersion")
//fasterxmlimplementation
compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jacksonDatatypeVersion")
//compile("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jacksonDataFormatXmlVersion")
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.8.8'
//jna依赖,否则项目启动时,会报classNotFound: native method disable的错误
compile("com.sun.jna:jna:$jnaVersion")
//阿里云 OSS
compile("com.aliyun.oss:aliyun-sdk-oss:${ossVersion}")
//阿里云 短信
compile("com.aliyun:aliyun-java-sdk-core:3.7.0")
//
compile("com.aliyun:aliyun-java-sdk-ecs:4.11.0")
//文件
compile("org.springframework:spring-mock:${mockVersion}")
//日志所需jar
compile group: 'org.slf4j', name: 'log4j-over-slf4j', version: '1.7.25'
//FastJson
compile("com.alibaba:fastjson:$fastJsonVersion")
//测试
testCompile("org.springframework.boot:spring-boot-starter-test")
//日志
compile("net.logstash.logback:logstash-logback-encoder:$EncodeVersion")
//启动
implementation("org.springframework.boot:spring-boot-starter")
//aop
implementation('org.springframework.boot:spring-boot-starter-aop')
//web
implementation ('org.springframework.boot:spring-boot-starter-web')
testImplementation ('org.springframework.boot:spring-boot-starter-test')
//swagger-ui
implementation("com.didispace:spring-boot-starter-swagger:$swaggerVersion") //API
}
package com.maxrocky;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 启动类
*/
@SpringBootApplication
public class BackServiceApplication {
public static void main(String[] args) {
SpringApplication.run(BackServiceApplication.class, args);
}
}
package com.maxrocky.common.config;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 跨域过滤器
*/
@Component
public class CrossFilter extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = {"*"};
registry.addMapping("/**")
.allowedOrigins(origins)
.allowCredentials(true)
.allowedMethods("*")
.maxAge(3600);
}
}
package com.maxrocky.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Leo
* @desc
* @date 2021/2/9 下午4:06
*/
@Component
public class CrossFilter1 implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//设置允许跨域的路径
.allowedOrigins("*")//设置允许跨域请求的域名
.allowCredentials(true)//是否允许证书 不再默认开启
.allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
.maxAge(3600);//跨域允许时间
}
}
package com.maxrocky.common.config;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 加载application-configuration.properties文件
*/
@Component
@PropertySource(value = {"exception.properties"}, encoding = "UTF-8")
public class LoadExceptionProperties {
}
package com.maxrocky.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc Swagger2 配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${swagger.show}")
private boolean swaggerShow;
/**
* @author YanChengLong
* @date 2019/3/27
* @desc 注入 Swagger2 bean
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerShow)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.maxrocky.rest"))
.paths(PathSelectors.any())
.build();
}
/**
* @author YanChengLong
* @date 2019/3/27
* @desc api输入
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("新创新平台 模块文档")
.description("新创新平台 模块文档示例")
.termsOfServiceUrl("https://yanchenglong.blog.csdn.net")
.version("1.0")
.build();
}
}
package com.maxrocky.common.tools;
import lombok.Data;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 自定义异常
*/
@Data
public class CustomException extends RuntimeException {
public CustomException(String code, String msg) {
super(code);
this.code = code;
this.msg = msg;
}
//错误码
private String code;
//错误提示信息
private String msg;
}
package com.maxrocky.common.tools;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 异常工厂
*/
@Component
public class ExceptionManager {
@Resource
Environment environment;
public CustomException create(String code) {
return new CustomException(code, environment.getProperty(code));
}
}
package com.maxrocky.common.tools;
import com.maxrocky.common.utils.apiresult.ApiResult;
import lombok.extern.log4j.Log4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Iterator;
/**
* @author YanChengLong
* @date 2019/3/27
* @desc 捕获异常
*/
@RestControllerAdvice
@Log4j
public class GlobalExceptionHandler {
@Resource
ExceptionManager exceptionManager;
/**
* 流程:1.判断是否是自定义异常
* 2.判断是否是 约束冲突异常
* 3.系统异常
*/
/**
* @author YanChengLong
* @date 2019/3/27
* @desc 捕获
*/
@ExceptionHandler(Exception.class)
public ApiResult handlerException(Exception e) {
//打印错误日志
log.error(logTraceInfo(e));
//如果是自定义的异常,或Validated的异常,返回对应的错误信息
if (e instanceof CustomException) {
CustomException exception = (CustomException) e;
return ApiResult.error(exception.getCode(), exception.getMsg());
//约束冲突异常
} else if (e instanceof ConstraintViolationException) {
log.error("ViolationException", e);
String code = "";
ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
Iterator<ConstraintViolation<?>> iterator = constraintViolationException.getConstraintViolations().iterator();
if (iterator.hasNext()) {
code = (iterator.next()).getMessageTemplate();
}
CustomException exception = exceptionManager.create(code);
return ApiResult.error(exception.getCode(), exception.getMsg());
} else {
//如果不是已知异常,返回系统异常
CustomException exception = new CustomException("SYS_EXCEPTION", "系统异常");
return ApiResult.error("SYS_EXCEPTION", "系统异常");
}
}
private String logTraceInfo(Exception e) {
StackTraceElement[] trace = e.getStackTrace();
StringBuilder sb = new StringBuilder();
sb.append(e);
for (StackTraceElement traceElement : trace) {
sb.append("\n\tat " + traceElement);
}
return sb.toString();
}
}
package com.maxrocky.rest;
import com.maxrocky.common.utils.apiresult.ApiResult;
import com.maxrocky.service.JinmaoWelfareService;
import com.maxrocky.service.dto.JinmaoWelfareGetSignRequestDTO;
import com.maxrocky.service.dto.JinmaoWelfareQuerySignRequestDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author Leo
* @desc
* @date 2021/2/9 上午10:16
*/
@RequestMapping(value = "/welfare", produces = "application/json")
@Api(value = "金茂福利红包", description = "金茂福利红包")
@RestController
public class JinmaoWelfareServiceRest {
@Resource
JinmaoWelfareService jinmaoWelfareService;
/**
* @author Leo
* @desc 获取序列号
* @date 2021/2/9 上午10:19
*/
@ApiOperation(value = "获取序列号", produces = "application/json")
@PostMapping(value = "/get/sign", produces = "application/json")
public ApiResult getSign(@RequestBody JinmaoWelfareGetSignRequestDTO jinmaoWelfareGetSignRequestDTO) {
return ApiResult.success(jinmaoWelfareService.getSign(jinmaoWelfareGetSignRequestDTO));
}
/**
* @author Leo
* @desc 查看序列号
* @date 2021/2/9 上午10:22
*/
@ApiOperation(value = "查看序列号", produces = "application/json")
@PostMapping(value = "/query/sign", produces = "application/json")
public ApiResult querySign(@RequestBody JinmaoWelfareQuerySignRequestDTO jinmaoWelfareQuerySignRequestDTO) {
return ApiResult.success(jinmaoWelfareService.querySign(jinmaoWelfareQuerySignRequestDTO));
}
}
package com.maxrocky.service;
import com.maxrocky.service.dto.JinmaoWelfareGetSignRequestDTO;
import com.maxrocky.service.dto.JinmaoWelfareQuerySignRequestDTO;
import javax.validation.Valid;
/**
* @author Leo
* @desc 业务
* @date 2021/2/9 上午10:08
*/
public interface JinmaoWelfareService {
/**
* @author Leo
* @desc 获取序列号
* @date 2021/2/9 上午10:28
*/
String getSign(@Valid JinmaoWelfareGetSignRequestDTO jinmaoWelfareGetSignRequestDTO);
/**
* @author Leo
* @desc 查看序列号
* @date 2021/2/9 上午10:31
*/
String querySign(@Valid JinmaoWelfareQuerySignRequestDTO jinmaoWelfareQuerySignRequestDTO);
}
package com.maxrocky.service;
import com.alibaba.fastjson.JSONObject;
import com.maxrocky.commom.RedisUtils;
import com.maxrocky.common.tools.ExceptionManager;
import com.maxrocky.service.dto.JinmaoWelfareGetSignRequestDTO;
import com.maxrocky.service.dto.JinmaoWelfareQuerySignRequestDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Objects;
/**
* @author Leo
* @desc 业务
* @date 2021/2/9 上午10:08
*/
@Service
public class JinmaoWelfareServiceImpl implements JinmaoWelfareService {
@Resource
ExceptionManager exceptionManager;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* @author Leo
* @desc 获取序列号
* @date 2021/2/9 上午10:37
*/
@Override
public String getSign(JinmaoWelfareGetSignRequestDTO jinmaoWelfareGetSignRequestDTO) {
if (Objects.isNull(jinmaoWelfareGetSignRequestDTO) || StringUtils.isBlank(jinmaoWelfareGetSignRequestDTO.getPhone())) {
throw exceptionManager.create("welfare_0001");
}
String code = "";
check(jinmaoWelfareGetSignRequestDTO.getPhone());
if (stringRedisTemplate.opsForHash().hasKey("redpacket:record", jinmaoWelfareGetSignRequestDTO.getPhone())) {
code = stringRedisTemplate.opsForHash().get("redpacket:record", jinmaoWelfareGetSignRequestDTO.getPhone()).toString();
} else {
if (!stringRedisTemplate.hasKey("redpacket:code")) {
throw exceptionManager.create("welfare_0003");
}
code = stringRedisTemplate.opsForList().leftPop("redpacket:code");
stringRedisTemplate.opsForHash().put("redpacket:record", jinmaoWelfareGetSignRequestDTO.getPhone(), code);
stringRedisTemplate.opsForHash().put("redpacket:userRecord", jinmaoWelfareGetSignRequestDTO.getPhone(), jinmaoWelfareGetSignRequestDTO.getSign());
}
return code;
}
/**
* @author Leo
* @desc 查看序列号
* @date 2021/2/9 上午10:37
*/
@Override
public String querySign(JinmaoWelfareQuerySignRequestDTO jinmaoWelfareQuerySignRequestDTO) {
if (Objects.isNull(jinmaoWelfareQuerySignRequestDTO) || StringUtils.isBlank(jinmaoWelfareQuerySignRequestDTO.getPhone())) {
throw exceptionManager.create("welfare_0001");
}
String code = null;
check(jinmaoWelfareQuerySignRequestDTO.getPhone());
if (stringRedisTemplate.opsForHash().hasKey("redpacket:record", jinmaoWelfareQuerySignRequestDTO.getPhone())) {
code = stringRedisTemplate.opsForHash().get("redpacket:record", jinmaoWelfareQuerySignRequestDTO.getPhone()).toString();
}
return code;
}
/**
* @author Leo
* @desc 认证
* @date 2021/2/9 上午11:34
*/
public void check(String phone) {
if (phone.length() != 11) {
throw exceptionManager.create("welfare_0002");
}
}
}
package com.maxrocky.service.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
/**
* @author Leo
* @desc
* @date 2021/2/9 上午10:25
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JinmaoWelfareGetSignRequestDTO {
//
@NotNull(message = "welfare_0001")
private String phone;
private String sign;
}
package com.maxrocky.service.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
/**
* @author Leo
* @desc
* @date 2021/2/9 上午10:30
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JinmaoWelfareQuerySignRequestDTO {
@NotNull(message = "welfare_0001")
private String phone;
}
${AnsiColor.CYAN}
${AnsiBackground.WHITE}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 佛祖保佑 永不宕机 永无BUG //
BACK ----- 服务
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
\ No newline at end of file
welfare_0001=未获取到用户信息
welfare_0002=请输入正确手机号
welfare_0003=兑换码领完啦!期待后续活动吧
\ No newline at end of file
package com.maxrocky;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BackServiceApplicationTests {
@Test
public void contextLoads() {
}
}
plugins {
id 'org.springframework.boot' version '2.1.7.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.maxrocky'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
//mavenCentral()
maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
jcenter()
}
jar {
baseName = 'common'
enabled = true
}
ext {
orikaVersion = '1.5.1'
fastJsonVersion = '1.2.35'
poiVersion='3.16'
jacksonVersion = '2.8.5'
jacksonDatatypeVersion = '2.8.8'
jacksonDataFormatXmlVersion = '2.8.8'
httpClientVersion='4.5.3'
itextpdfVersion='5.4.3'
itextpdfAsian='5.2.0'
commonslang3Version='3.6'
aliyunOssVersion='2.8.1'
zxingVersion = '3.2.1'
}
dependencies {
//web
compile 'org.springframework.boot:spring-boot-starter-web'
//POI
compile ("org.apache.poi:poi:$poiVersion")
compile ("org.apache.poi:poi-ooxml:$poiVersion")
compile('org.springframework.boot:spring-boot-starter')
//配置mapperFactory
compile("ma.glasnost.orika:orika-core:$orikaVersion")
//Lombok自动生成重复代码
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
//httpclient
compile ("org.apache.httpcomponents:httpclient:$httpClientVersion")
compile ("org.apache.httpcomponents:httpcore:4.4.8")
//FastJson
compile("com.alibaba:fastjson:$fastJsonVersion")
//jackson
compile ("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
compile ("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jacksonDatatypeVersion")
compile ("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jacksonDataFormatXmlVersion")
//
compile("com.sun.jna:jna:3.0.9")
//compile("com.itextpdf:itextpdf:$itextpdfVersion")
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.4.3'
//compile("com.itextpdf:itext-asian:$itextpdfAsian")
compile("org.apache.commons:commons-lang3:$commonslang3Version")
compile("com.aliyun.oss:aliyun-sdk-oss:$aliyunOssVersion")
//二维码
compile("com.google.zxing:javase:${zxingVersion}")
//条形码
compile fileTree(dir:'lib',include:['*.jar'])
//测试
testCompile 'org.springframework.boot:spring-boot-starter-test'
//
compile("commons-io:commons-io:2.4")
}
package com.maxrocky.common;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 工具类
*/
@SpringBootApplication
public class CommonApplication {
public static void main(String[] args) {
SpringApplication.run(CommonApplication.class, args);
}
}
package com.maxrocky.common.config;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 配置日志中显示IP
*/
public class IPLogConfig extends ClassicConverter {
@Override
public String convert(ILoggingEvent event) {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
}
package com.maxrocky.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.Assert;
public class ConfigUtil {
@Autowired
private static Environment env;
static {
env = SpringContextHolder.getBean(Environment.class);
}
public static boolean getBoolean(String paramString) {
return Boolean.valueOf(env.getProperty(paramString, "false"));
}
public static int getInt(String paramString) {
String property = env.getProperty(paramString);
Assert.notNull(property);
return Integer.parseInt(property);
}
public static int getInt(String paramString, int defaultValue) {
String property = env.getProperty(paramString);
if (StringUtils.isNotBlank(property)) {
Integer.parseInt(property.trim());
}
return defaultValue;
}
public static double getDouble(String paramString, double defaultValue) {
String property = env.getProperty(paramString);
if (StringUtils.isNotBlank(property)) {
Double.parseDouble(property.trim());
}
return defaultValue;
}
public static long getLong(String paramString) {
String property = env.getProperty(paramString);
Assert.notNull(property);
return Long.parseLong(property);
}
public static String getString(String paramString) {
return env.getProperty(paramString);
}
public static String getString(String paramString, String defaultValue) {
String property = env.getProperty(paramString);
if (StringUtils.isNotBlank(property)) {
return property;
}
return defaultValue;
}
public static String[] getStringArray(String paramString) {
String property = env.getProperty(paramString);
Assert.notNull(property);
return property.split(",");
}
}
package com.maxrocky.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取全局容器对象ApplicationContext
* 获取指定bean
* @author QLJ
* @since jdk1.8
* @version 1.0.0
* @see ApplicationContextAware
*
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public ApplicationContext getApplicationContext(){
return SpringContextHolder.applicationContext;
}
public static <T> T getBean(String beanName, Class<T> beanType){
assertApplicationContext();
return applicationContext.getBean(beanName, beanType);
}
public static <T> T getBean(Class<T> beanType) {
assertApplicationContext();
return applicationContext.getBean(beanType);
}
private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
package com.maxrocky.common.utils.apiresult;
import lombok.Data;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 返回
*/
@Data
public abstract class ApiResult {
protected String code;
/**
* 成功的返回
*
* @param data 数据
* @return 正常返回体
*/
public static ApiResult success(Object data) {
return new SuccessApiResult(data);
}
/**
* 错误返回
*
* @param errorCode 错误码
* @param errorMessage 错误信息
* @return 错误返回体
*/
public static ApiResult error(String errorCode, String errorMessage) {
return new ErrorApiResult(errorCode, errorMessage);
}
}
package com.maxrocky.common.utils.apiresult;
import lombok.Data;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 错误返回
*/
@Data
public class ErrorApiResult extends ApiResult {
private String msg;
ErrorApiResult(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
package com.maxrocky.common.utils.apiresult;
import lombok.Data;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 正确返回体
*/
@Data
public class SuccessApiResult extends ApiResult {
private Object data;
SuccessApiResult(Object data) {
this.code = "0";
this.data = data;
}
}
package com.maxrocky.common.utils.date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Date;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc java8日期工具
*/
public final class LocalDateTimeUtils {
private LocalDateTimeUtils() { }
//获取当前时间的LocalDateTime对象
//LocalDateTime.now();
//根据年月日构建LocalDateTime
//LocalDateTime.of();
//比较日期先后
//LocalDateTime.now().isBefore(),
//LocalDateTime.now().isAfter(),
//Date转换为LocalDateTime
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
//LocalDateTime转换为Date
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
//获取指定日期的毫秒
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
//获取指定日期的秒
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
//获取指定时间的指定格式
public static String formatTime(LocalDateTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
//获取当前时间的指定格式
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
//日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
//日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
}
/**
* 获取两个日期的差 field参数为ChronoUnit.*
* @param startTime
* @param endTime
* @param field 单位(年月日时分秒)
* @return
*/
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) {
return period.getYears();
}
if (field == ChronoUnit.MONTHS) {
return period.getYears() * 12 + period.getMonths();
}
return field.between(startTime, endTime);
}
//获取一天的开始时间,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);
}
/**
* @author YanChengLong
* @date 2017/12/5 0:59
* @desc 两个时间相减
*/
public static Long getTimeSubtraction(LocalDateTime stateTime, LocalDateTime endTime) {
return endTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond() - stateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
}
package com.maxrocky.common.utils.des;
import org.apache.commons.io.IOUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/10/17
* @desc des 加密
*/
public final class DesCryptUtils {
//code
private static String CODE_TYPE = "UTF-8";
/**
* DES加密
* @param datasource
* @return
*/
public static String encode(String datasource, String key){
try{
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key.getBytes(CODE_TYPE));
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
//Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
//现在,获取数据并加密
byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes()));
return IOUtils.toString(temp,"UTF-8");
}catch(Throwable e){
e.printStackTrace();
return null;
}
}
/**
* DES解密
* @return
*/
public static String decode(String src, String key) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom random = new SecureRandom();
// 创建一个DESKeySpec对象
DESKeySpec desKey = new DESKeySpec(key.getBytes(CODE_TYPE));
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 将DESKeySpec对象转换成SecretKey对象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正开始解密操作
return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src)),"UTF-8");
}
}
package com.maxrocky.common.utils.excel;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc Excel注解,用以生成Excel表格文件.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface Excel {
//列名
String name() default "";
//宽度
int width() default 25;
//忽略该字段
boolean skip() default false;
//日期格式
String dateFormat() default "yyyy年MM月dd日 HH:mm";
String merge() default "";
}
package com.maxrocky.common.utils.excel;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 设置Excel的样式
*/
public class ExcelStyle {
public ExcelStyle() { }
//对齐方式
private HorizontalAlignment align;
//字体 "黑体"等
private String fontName;
//是否加粗,对表头不生效
private boolean isBold;
//字体大小
private short size;
//字体颜色
private short fontColor;
//边框粗细
private BorderStyle borderStyle;
//背景颜色
private short backColor;
public ExcelStyle setAlign(HorizontalAlignment align) {
this.align = align;
return this;
}
public ExcelStyle setFontName(String fontName) {
this.fontName = fontName;
return this;
}
public ExcelStyle setBold(boolean bold) {
isBold = bold;
return this;
}
public ExcelStyle setSize(short size) {
this.size = size;
return this;
}
public ExcelStyle setFontColor(short fontColor) {
this.fontColor = fontColor;
return this;
}
public ExcelStyle setBorderStyle(BorderStyle borderStyle) {
this.borderStyle = borderStyle;
return this;
}
public ExcelStyle setBackColor(short backColor) {
this.backColor = backColor;
return this;
}
public HorizontalAlignment getAlign() {
return align;
}
public String getFontName() {
return fontName;
}
public boolean isBold() {
return isBold;
}
public short getSize() {
return size;
}
public short getFontColor() {
return fontColor;
}
public BorderStyle getBorderStyle() {
return borderStyle;
}
public short getBackColor() {
return backColor;
}
}
package com.maxrocky.common.utils.excel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 合并单元格载体
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MergeExcelDTO {
private Integer startRow;
private Integer endRow;
private Integer startLine;
private Integer endLine;
public void addRow(){
this.endRow = endRow + 1;
}
}
\ No newline at end of file
package com.maxrocky.common.utils.file;
/**
* @author YanChengLong
* @date 2019/12/4
* @desc 文件限制
*/
public class FileUtil {
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/12/4
* @desc 文件长度 限制大小 限制单位(B,K,M,G)
*/
public static boolean checkFileSize(Long len, int size, String unit) {
// long len = file.length();
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) len;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) len / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) len / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) len / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
}
package com.maxrocky.common.utils.ip;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* @author YanChengLong
* @date 2019/9/26
* @desc 获取IP
*/
public final class IpUtils {
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/9/26
* @desc 获取IP地址
*/
public final static String getIpAddress(HttpServletRequest request) {
String Xip = request.getHeader("X-Real-IP");
String XFor = request.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
//多次反向代理后会有多个ip值,第一个ip才是真实ip
int index = XFor.indexOf(",");
if (index != -1) {
return XFor.substring(0, index);
} else {
return XFor;
}
}
XFor = Xip;
if (StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)) {
return XFor;
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
XFor = request.getRemoteAddr();
}
return XFor;
}
/*首先,我们获取 X-Forwarded-For 中第0位的IP地址,它就是在HTTP扩展协议中能表示真实的客户端IP。
因为,一般情况下我们的服务都是经过Nginx转发的,也或者还不止一台Nginx一次转发,
所以我们获取到的 X-Forwarded-For 其实是一个数组,但第0位才是用户真实IP,其余的都是Nginx转发的地址:
*/
public final static String getIpAddress1(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
package com.maxrocky.common.utils.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc Json工具
*/
public final class JsonUtils {
private JsonUtils() {
}
/**
* json串转换为对象
*
* @param json
* @param clazz
* @param <T>
* @return
*/
public static <T> T jsonToBean(String json, Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
/**
* 对象转换为json,可以带上date的格式化
*
* @param object
* @return
*/
public static String beanToJson(Object object, String dateFormat) {
if (Objects.isNull(dateFormat) || "".equals(dateFormat)) {
return JSON.toJSONString(object);
}
return JSON.toJSONStringWithDateFormat(object, dateFormat);
}
/**
* json返回List
*
* @param arrayJson
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> jsonToList(String arrayJson, Class<T> clazz, String dateFormat) {
String temp = JSONObject.DEFFAULT_DATE_FORMAT;
if (!"".equals(dateFormat) && dateFormat != null) {
JSONObject.DEFFAULT_DATE_FORMAT = dateFormat;
}
List<T> list = JSON.parseArray(arrayJson, clazz);
JSONObject.DEFFAULT_DATE_FORMAT = temp;
return list;
}
// /**
// * 反序列化Map
// * @param mapJson
// * @param <K>
// * @param <V>
// * @return
// */
// public static <K, V> Map jsonMap(String mapJson, Class<K> keyType, Class<V> valueType) {
// return JSON.parseObject(mapJson, new TypeReference<Map<K, V>>() { });
// }
public static <T> T toBean(String json, TypeReference typeReference) {
T result = null;
ObjectMapper objectMapper = new ObjectMapper();
//忽略多余属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//序列化ArrayList
objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
objectMapper.registerModule(new JavaTimeModule());
try {
result = objectMapper.readValue(json, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String toJson(Object object) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
String result = null;
try {
result = objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
}
package com.maxrocky.common.utils.mapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 属性映射工具
*/
public final class MapperUtils {
private MapperUtils() { }
/**
* 构建一个Mapper工厂
*/
private static final MapperFactory MAPPER_FACTORY = new DefaultMapperFactory.Builder().build();
/**
* 将s属性映射到R的具体实例上
* @param s 已有的Bean,源Bean
* @param rClass
* @param <S> sourceBean
* @param <R> ReturnBean
* @return R的实例
*/
public static <S, R> R mapperBean(S s, Class<R> rClass) {
return MAPPER_FACTORY.getMapperFacade().map(s, rClass);
}
/**
* 将s属性映射到R的具体实例上,如果转换的属性名不一样,可以传入Map进行说明
* @param s 已有的Bean,源Bean
* @param rClass
* @param <S> sourceBean
* @param <R> ReturnBean
* @return R的实例
*/
public static <S, R> R mapperBean(S s, Class<R> rClass, Map<String, String> diffFieldMap) {
ClassMapBuilder<?, R> classMap = MAPPER_FACTORY.classMap(s.getClass(), rClass);
diffFieldMap.forEach(classMap::field);
classMap.byDefault()
.register();
return MAPPER_FACTORY.getMapperFacade().map(s, rClass);
}
/**
* 将s的集合射成R的集合
* @param sList 已有的Bean的集合
* @param rClass 要转换的类型
* @param <S> sourceBean
* @param <R> ReturnBean
* @return R的实例
*/
public static <S, R> List<R> mapperList(List<S> sList, Class<R> rClass) {
return MAPPER_FACTORY.getMapperFacade().mapAsList(sList, rClass);
}
/**
* 将s的集合射成R的集合,不同的属性通过Map<String, String> 传入
* @param sList 已有的Bean的集合
* @param rClass 要转换的类型
* @param <S> sourceBean
* @param <R> ReturnBean
* @return R的实例
*/
public static <S, R> List<R> mapperList(List<S> sList, Class<R> rClass, Map<String, String> diffFieldMap) {
if (sList.isEmpty()) {
return Collections.emptyList();
}
ClassMapBuilder<?, R> classMap = MAPPER_FACTORY.classMap(sList.get(0).getClass(), rClass);
diffFieldMap.forEach(classMap::field);
classMap.byDefault()
.register();
return MAPPER_FACTORY.getMapperFacade().mapAsList(sList, rClass);
}
}
package com.maxrocky.common.utils.md5;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc MD5工具类, 全部接收UTF编码的String
*/
public final class MD5Utils {
private MD5Utils() { }
private static final String ALGORITHM_MD5 = "MD5";
private static final String UTF_8 = "UTF-8";
/**
* MD5 16bit 小写.
* @param readyEncryptStr ready encrypt string
* @return String encrypt result string
* @throws NoSuchAlgorithmException
* */
public static String md5Bit16Lower(String readyEncryptStr) throws Exception {
if (Objects.nonNull(readyEncryptStr)) {
return MD5Utils.md5Bit32Lower(readyEncryptStr).substring(8, 24);
} else {
return null;
}
}
/**
* MD5 16bit 大写.
* @param readyEncryptStr ready encrypt string
* @return String encrypt result string
* @throws NoSuchAlgorithmException
* */
public static String md5Bit16Upper(String readyEncryptStr) throws Exception {
return md5Bit16Lower(readyEncryptStr).toUpperCase();
}
/**
* MD5 32bit 小写.
* @param readyEncryptStr ready encrypt string
* @return String encrypt result string
* @throws NoSuchAlgorithmException
* */
public static String md5Bit32Lower(String readyEncryptStr) throws Exception {
if (Objects.nonNull(readyEncryptStr)) {
MessageDigest md = MessageDigest.getInstance(ALGORITHM_MD5);
md.update(readyEncryptStr.getBytes(UTF_8));
byte[] b = md.digest();
StringBuilder su = new StringBuilder();
for (int offset = 0, bLen = b.length; offset < bLen; offset++) {
String haxHex = Integer.toHexString(b[offset] & 0xFF);
if (haxHex.length() < 2) {
su.append("0");
}
su.append(haxHex);
}
return su.toString();
} else {
return null;
}
}
/**
* MD5 32bit 大写.
* @param readyEncryptStr ready encrypt string
* @return String encrypt result string
* @throws NoSuchAlgorithmException
* */
public static String md5Bit32Upper(String readyEncryptStr) throws Exception {
return md5Bit32Lower(readyEncryptStr).toUpperCase();
}
}
package com.maxrocky.common.utils.oss;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.maxrocky.common.utils.ConfigUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.StreamUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* aliyun oss操作
* @author QLJ
* @version 1.0
* @since jdk1.8
*/
public class OssClientUtils {
private static String endpoint = ConfigUtil.getString("END_POINT","oss-cn-shenzhen.aliyuncs.com");
private static String accessKeyId = ConfigUtil.getString("ACCESS_KEY","LTAIHwGmHnGxVyoa");
private static String accessKeySecret = ConfigUtil.getString("ACCESS_SEC","k1KZRnqVPgyE0OPI53UFHbmv7kV2tQ");
private static String bucketName = ConfigUtil.getString("BUCKET_NAME","fhyx-production");
public static void putObject(String keySuffix, String key, InputStream inputStream){
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 上传图片
keySuffix = keySuffix + "/";
ossClient.putObject(bucketName, keySuffix, new ByteArrayInputStream(new byte[0]));
ossClient.putObject(bucketName, keySuffix + key, inputStream);
// 关闭client
ossClient.shutdown();
}
public static void putImage(String imgName, String base64Img){
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 上传图片
byte[] decoderBytes = Base64.decodeBase64(base64Img);
ossClient.putObject(bucketName, imgName, new ByteArrayInputStream(decoderBytes));
// 关闭client
ossClient.shutdown();
}
public static void delImage(String key){
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.deleteObject(bucketName, key);
// 关闭client
ossClient.shutdown();
}
public static String getObject(String key) throws IOException{
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(bucketName, key);
byte[] bArrCont = StreamUtils.copyToByteArray(ossObject.getObjectContent());
return new String(bArrCont);
}
public static InputStream getContentInputStream(String key) throws IOException{
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(bucketName, key);
return ossObject.getObjectContent();
}
public static String getFileUrl(String keySuffix, String key) throws IOException{
// 创建OSSClient实例
keySuffix = keySuffix + "/";
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(bucketName, keySuffix + key);
String dat = ossObject.getResponse().getUri();
return dat;
}
}
package com.maxrocky.common.utils.page;
import lombok.Data;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 分页请求参数封装
*/
@Data
public class PageParam {
public static final int PAGE_SIZE = 10;
public PageParam() {
this.c = PAGE_SIZE;
}
public PageParam(Integer p, Integer c) {
this.setP(p);
this.setC(c);
}
//当前页
private Integer p = 0;
//每页容量
private Integer c;
public int firstResult() {
return (p - 1) * c;
}
public Integer getP() {
return p;
}
public void setP(Integer p) {
if (p != null) {
this.p = p;
}
}
public Integer getC() {
return c;
}
public void setC(Integer c) {
if (c != null) {
this.c = c;
}
}
}
package com.maxrocky.common.utils.page;
import java.util.List;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 分页容器
*/
public class PageResult<T> {
private PageResult() { }
//当前页
private Integer page;
//总数量
private Integer count;
//分页数据
private List<T> list;
public PageResult(int page, int count, List<T> list) {
this.page = page;
this.count = count;
this.list = list;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}
package com.maxrocky.common.utils.page;
import com.maxrocky.common.utils.mapper.MapperUtils;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc PageResult
*/
@Component
public class PageResultFactory {
public <T> PageResult createPageResult(int page, int count, List<T> data) {
return new PageResult<T>(page, count, data);
}
public <E> PageResult<E> convert(PageResult pageResult, Class<E> dtoClass) {
List<E> dtoList = MapperUtils.mapperList(pageResult.getList(), dtoClass);
return new PageResult<E>(pageResult.getPage(), pageResult.getCount(), dtoList);
}
public <T, E> PageResult<E> convert(PageResult<T> pageResult, Function<T, E> function) {
return new PageResult<E>(pageResult.getPage(), pageResult.getCount(),
pageResult.getList().stream().map(function).collect(Collectors.toList()));
}
}
package com.maxrocky.common.utils.random;
import java.util.Random;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 随机生成工具类
*/
public final class RandomUtils {
private RandomUtils() { }
private static Random random = new Random();
/**
* 获取一个固定长度的随机整数,可当做验证码。
* @param size 长度
* @return String
*/
public static String getRandomNum(int size) {
return String.valueOf(Math.random()).substring(2, size + 2);
}
/**
* 获取两个数的中间数,包含min和max
* @param min 最小
* @param max 最大
* @return 中间数
*/
public static int getMidNum(int min, int max) {
return min + random.nextInt(max - min + 1);
}
}
package com.maxrocky.common.utils.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc 正则
*/
public final class RegexUtils {
private RegexUtils() { }
/**
* @param mobiles
* @return isMobileNO
* @description 校验手机号是否正确
*/
public static boolean isMobileNO(String mobiles) {
String str = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(mobiles);
return m.matches();
}
/**
* @param email
* @return isEmail
* @description 校验邮箱是否正确
*/
public static boolean isEmail(String email) {
String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
/**
* @param value
* @return isInteger
* @description 校验是否是整数
*/
public static boolean isInteger(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* 判断是否含有特殊字符
* @param text
* @return boolean true,通过,false,没通过
*/
public static boolean hasSpecialChar(String text) {
if (null == text || "".equals(text)) {
return true;
}
if (text.replaceAll("[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() == 0) {
// 如果不包含特殊字符
return false;
}
return true;
}
/**
* 判断是否正整数
* @param number 数字
* @return boolean true,通过,false,没通过
*/
public static boolean isNumber(String number) {
if (null == number || "".equals(number)) {
return false;
}
String regex = "[0-9]*";
return number.matches(regex);
}
/**
* 判断是否是正确的IP地址
* @param ip
* @return boolean true,通过,false,没通过
*/
public static boolean isIp(String ip) {
if (null == ip || "".equals(ip)) {
return false;
}
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
return ip.matches(regex);
}
/**
* 判断是否含有中文,仅适合中国汉字,不包括标点
* @param text
* @return boolean true,通过,false,没通过
*/
public static boolean isChinese(String text) {
if (null == text || "".equals(text)) {
return false;
}
String regex = "[\u4e00-\u9fa5]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
return m.find();
}
}
package com.maxrocky.common.utils.sort;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author wangzhaoyu@maxrocky.com
* @date 2018-11-23 14:43
* @desc .
*/
public class ChineseCharactersSort {
//字母Z使用了两个标签,这里有27个值
//i, u, v都不做声母, 跟随前面的字母
private char[] chartable =
{
'啊', '芭', '擦', '搭', '蛾', '发', '噶', '哈', '哈',
'击', '喀', '垃', '妈', '拿', '哦', '啪', '期', '然',
'撒', '塌', '塌', '塌', '挖', '昔', '压', '匝', '座'
};
private char[] alphatableb =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
private char[] alphatables =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
};
private int[] table = new int[27]; //初始化
{
for (int i = 0; i < 27; ++i) {
table[i] = gbValue(chartable[i]);
}
}
//主函数,输入字符,得到他的声母,
//英文字母返回对应的大小写字母
//其他非简体汉字返回 '0' 按参数
public char char2Alpha(char ch, String type) {
if (ch >= 'a' && ch <= 'z') {
return (char) (ch - 'a' + 'A');//为了按字母排序先返回大写字母
}
if (ch >= 'A' && ch <= 'Z') {
return ch;
}
int gb = gbValue(ch);
if (gb < table[0]) {
return '0';
}
int i;
for (i = 0; i < 26; ++i) {
if (match(i, gb)) {
break;
}
}
if (i >= 26) {
return '0';
} else {
if ("b".equals(type)) {//大写
return alphatableb[i];
} else {//小写
return alphatables[i];
}
}
}
//根据一个包含汉字的字符串返回一个汉字拼音首字母的字符串
public String string2Alpha(String sourceStr, String type) {
String result = "";
int strLength = sourceStr.length();
int i;
try {
for (i = 0; i < strLength; i++) {
result += char2Alpha(sourceStr.charAt(i), type);
}
} catch (Exception e) {
result = "";
}
return result;
}
//根据一个包含汉字的字符串返回第一个汉字拼音首字母的字符串
public String string2AlphaFirst(String sourceStr, String type) {
String result = "";
try {
result += char2Alpha(sourceStr.charAt(0), type);
} catch (Exception e) {
result = "";
}
return result;
}
private boolean match(int i, int gb) {
if (gb < table[i]) {
return false;
}
int j = i + 1;
//字母Z使用了两个标签
while (j < 26 && (table[j] == table[i])) {
++j;
}
if (j == 26) {
return gb <= table[j];
} else {
return gb < table[j];
}
}
//取出汉字的编码
private int gbValue(char ch) {
String str = "";
str += ch;
try {
byte[] bytes = str.getBytes("GBK");
if (bytes.length < 2) {
return 0;
}
return (bytes[0] << 8 & 0xff00) + (bytes[1] &
0xff);
} catch (Exception e) {
return 0;
}
}
public Map sort(List<String> list) {
Map<String, List<String>> map = new HashMap<>();
List<String> arraylist = new ArrayList<>();
String[] alphaTableb =
{
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
};
for (String a : alphaTableb) {
for (int i = 0; i < list.size(); i++) {//为了排序都返回大写字母
if (a.equals(string2AlphaFirst(list.get(i).toString(), "b"))) {
arraylist.add(list.get(i).toString());
}
}
map.put(a, arraylist);
arraylist = new ArrayList<>();
}
return map;
}
}
package com.maxrocky.common.utils.uuid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/8/27
* @desc uuid生成
*/
public final class UUIDUtils {
private UUIDUtils() {
}
/**
* 获取UUID,不含有-
*
* @return
*/
public static String getUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 批量获取UUID
*
* @param size
* @return
*/
public static ArrayList getUUIDList(int size) {
return Stream.iterate(1, item -> item + 1)
.limit(size)
.map(item -> getUUID())
.collect(Collectors.toCollection(ArrayList::new));
}
/**
* 订单生成策略
*
* @return
*/
public static String getOrderUUID() {
String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
String system = String.valueOf(System.nanoTime()).
substring(
(String.valueOf(System.nanoTime()).length() - 4),
String.valueOf(System.nanoTime()).length());
return date + system;
}
/**
* 生成短信验证码
*
* @return
*/
public static String getVerifyCode() {
return String.valueOf((int)((Math.random()*9+1)*100000));
}
}
package com.maxrocky.common.utils.xml;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.ByteArrayOutputStream;
/**
* @author jepson
* @date 2017/11/20 14:40
* @desc xml工具类
*/
public class XmlUtils {
public static <T> String getXml(Class<T> clazz, T o){
String xmlObj = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz); // 获取上下文对象
Marshaller marshaller = context.createMarshaller(); // 根据上下文获取marshaller对象
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 设置编码字符集
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出,有分行和缩进
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(o, baos);
return new String(baos.toByteArray()); // 生成XML字符串
} catch (Exception ex) {
}
return null;
}
}
plugins {
id 'org.springframework.boot' version '2.1.5.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'
group = 'com.maxrocky'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
jar {
baseName = "redis"
enabled = true
}
dependencies {
//引用 依赖工具类
compile project(':common')
compile 'org.springframework.boot:spring-boot-starter-data-redis'
compile 'org.springframework.boot:spring-boot-starter-web'
testCompile 'org.springframework.boot:spring-boot-starter-test'
}
package com.maxrocky;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author YanChengLong yanchenglong.blog.csdn.net
* @date 2019/10/14
* @desc 启动类
*/
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
package com.maxrocky.commom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author YanChengLong
* @date 2019/4/1
* @desc 工具类redis
*/
@Component
public class RedisUtils {
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
@SuppressWarnings("unchecked")
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
}
/**
* 删除对应的value
*
* @param key
*/
@SuppressWarnings("unchecked")
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
* makeboLo678 或ygbh14052
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param key
* @return
* @desc 自增1
*/
public void increase(String key) {
redisTemplate.opsForValue().increment(key, 1);
}
/**
* 新增集合
*
* @param key
*/
public void insertSet(String key, String value) {
redisTemplate.opsForSet().add(key, value);
}
/**
* @param key
* @return
* @desc 查询集合数量
*/
public Long querySetCount(String key) {
return redisTemplate.opsForSet().size(key);
}
/**
* @param key
* @desc 删除集合
*/
public void popSet(String key) {
redisTemplate.opsForSet().pop(key);
}
}
package com.maxrocky.redis.config;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @author YanChengLong
* @date 2019/4/1
* @desc 引入redis配置文件
*/
@PropertySource(value = "application-redis.properties")
@Component
public class LoadRedisProperties {
}
package com.maxrocky.redis.config;
import javax.annotation.Resource;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
/**
* @author YanChengLong
* @date 2019/4/1
* @desc redis 的bean注入
*/
@Configuration
@EnableCaching //启用缓存
public class RedisCacheConfig extends CachingConfigurerSupport {
@Resource
private LettuceConnectionFactory lettuceConnectionFactory;
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuffer sb = new StringBuffer();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
// 缓存管理器
@Bean
public CacheManager cacheManager() {
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(lettuceConnectionFactory);
@SuppressWarnings("serial")
Set<String> cacheNames = new HashSet<String>() {
{
add("codeNameCache");
}
};
builder.initialCacheNames(cacheNames);
return builder.build();
}
/**
* @author YanChengLong
* @date 2019/7/15
* @desc RedisTemplate配置
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
\ No newline at end of file
# Redis数据库索引(默认为0)
#spring.redis.database=0
# Redis服务器地址
spring.redis.host=60.205.219.165
# Redis服务器连接端口
spring.redis.port=5888
# Redis服务器连接密码
spring.redis.password=MaxRocky5721!@#
# 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
#spring.redis.timeout=0
\ No newline at end of file
rootProject.name = 'welfare'
// 后台服务
include 'back-service'
// 工具类
include 'common'
// 缓存
include 'redis'
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment