Commit d8f8b8fd by houseme

添加日志记录 以及拦截处理!

parent 4d115eb5
...@@ -29,3 +29,4 @@ build/ ...@@ -29,3 +29,4 @@ build/
### VS Code ### ### VS Code ###
.vscode/ .vscode/
data
\ No newline at end of file
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<dependencySets>
<dependencySet>
<useProjectArtifact>false</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>compile</scope>
</dependencySet>
</dependencySets>
<fileSets>
<fileSet>
<filtered>true</filtered>
<directory>src/main/resources</directory>
<outputDirectory>/configs</outputDirectory>
<excludes>
<exclude>dev/*</exclude>
<exclude>test/*</exclude>
<exclude>pro/*</exclude>
</excludes>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</fileSet>
<fileSet>
<filtered>true</filtered>
<directory>src/main/resources/${profiles.active}</directory>
<outputDirectory>/configs</outputDirectory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
</fileSet>
<fileSet>
<filtered>true</filtered>
<directory>scripts</directory>
<outputDirectory>/bin</outputDirectory>
</fileSet>
<fileSet>
<directory>target</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
<excludes>
<exclude>*sources.jar</exclude>
</excludes>
</fileSet>
</fileSets>
</assembly>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.M4</version> <version>2.2.0.M4</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
<groupId>com.lanren.huhu</groupId> <groupId>com.lanren.huhu</groupId>
<artifactId>partner</artifactId> <artifactId>partner</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>partner</name> <name>partner</name>
<description>呼呼省钱合伙人相关服务</description> <description>呼呼省钱合伙人相关服务</description>
<packaging>jar</packaging>
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mainClass>com.lanren.huhu.partner.PartnerApplication</mainClass>
<todir>./data/release/${profiles.active}/</todir>
</properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> <artifactId>spring-boot-starter-aop</artifactId>
</dependency> <version>2.2.0.M4</version>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <dependency>
<artifactId>spring-boot-starter-web</artifactId> <groupId>org.springframework.boot</groupId>
</dependency> <artifactId>spring-boot-starter-data-redis</artifactId>
<dependency> </dependency>
<groupId>org.mybatis.spring.boot</groupId> <dependency>
<artifactId>mybatis-spring-boot-starter</artifactId> <groupId>org.springframework.boot</groupId>
<version>2.0.1</version> <artifactId>spring-boot-starter-web</artifactId>
</dependency> <exclusions>
<!--添加通用Mapper依赖 --> <exclusion>
<!--<dependency>--> <artifactId>jackson-databind</artifactId>
<!--<groupId>tk.mybatis</groupId>--> <groupId>com.fasterxml.jackson.core</groupId>
<!--<artifactId>mapper-spring-boot-starter</artifactId>--> </exclusion>
<!--<version>1.1.4</version>--> </exclusions>
<!--</dependency>--> </dependency>
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
<scope>runtime</scope> <version>2.0.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>mysql</groupId>
<artifactId>lombok</artifactId> <artifactId>mysql-connector-java</artifactId>
<scope>provided</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId> <artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version> <version>3.1.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId> <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency> <scope>provided</scope>
<!--<dependency>--> </dependency>
<!--<groupId>org.springframework.boot</groupId>--> <dependency>
<!--<artifactId>spring-boot-starter-test</artifactId>--> <groupId>org.springframework.boot</groupId>
<!--<scope>test</scope>--> <artifactId>spring-boot-starter-test</artifactId>
<!--<exclusions>--> <scope>test</scope>
<!--<exclusion>--> </dependency>
<!--<groupId>org.junit.vintage</groupId>--> <dependency>
<!--<artifactId>junit-vintage-engine</artifactId>--> <groupId>org.apache.commons</groupId>
<!--</exclusion>--> <artifactId>commons-pool2</artifactId>
<!--<exclusion>--> <version>2.6.2</version>
<!--<groupId>junit</groupId>--> </dependency>
<!--<artifactId>junit</artifactId>--> <dependency>
<!--</exclusion>--> <groupId>org.springframework.boot</groupId>
<!--</exclusions>--> <artifactId>spring-boot-devtools</artifactId>
<!--</dependency>--> <scope>runtime</scope>
</dependencies> </dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
<build> <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<plugins> <dependency>
<plugin> <groupId>com.alibaba</groupId>
<groupId>org.springframework.boot</groupId> <artifactId>druid-spring-boot-starter</artifactId>
<artifactId>spring-boot-maven-plugin</artifactId> <version>1.1.17</version>
</plugin> </dependency>
</plugins> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
</build> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<repositories> <profiles>
<repository> <profile>
<id>spring-snapshots</id> <!-- 本地开发环境 -->
<name>Spring Snapshots</name> <id>dev</id>
<url>https://repo.spring.io/snapshot</url> <properties>
<snapshots> <profiles.active>dev</profiles.active>
<enabled>true</enabled> <mysql.server>jdbc:mysql://10.9.121.204:3306/huhu</mysql.server>
</snapshots> <mysql.username>yanfa</mysql.username>
</repository> <mysql.password>cScdKw%ZKC1i$C!1uAz3Kg$c</mysql.password>
<repository> <redis.host>10.9.186.167</redis.host>
<id>spring-milestones</id> <redis.password>passwdredis</redis.password>
<name>Spring Milestones</name> <spring.profiles.active>dev</spring.profiles.active>
<url>https://repo.spring.io/milestone</url> <logfile_path>./data/logs/huhu/lanren</logfile_path>
</repository> <providers-path>/data/java/service</providers-path>
</repositories> </properties>
<pluginRepositories> <!-- 默认是本地开发环境 -->
<pluginRepository> <activation>
<id>spring-snapshots</id> <activeByDefault>true</activeByDefault>
<name>Spring Snapshots</name> </activation>
<url>https://repo.spring.io/snapshot</url> </profile>
<snapshots> <profile>
<enabled>true</enabled> <!-- 测试环境 -->
</snapshots> <id>test</id>
</pluginRepository> <properties>
<pluginRepository> <profiles.active>test</profiles.active>
<id>spring-milestones</id> </properties>
<name>Spring Milestones</name> </profile>
<url>https://repo.spring.io/milestone</url> <profile>
</pluginRepository> <!-- 生产环境 -->
</pluginRepositories> <id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
<mysql.server>jdbc:mysql://172.21.0.4:3306/huhu</mysql.server>
<mysql.username>huhu</mysql.username>
<mysql.password>huhu</mysql.password>
<redis.host>172.21.0.17</redis.host>
<redis.password>huhu</redis.password>
<spring.profiles.active>prod</spring.profiles.active>
<logfile_path>/data/logs/huhu/lanren</logfile_path>
<providers-path>/data/java/service</providers-path>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>${mainClass}</mainClass>
</manifest>
<manifestEntries>
<Class-Path>configs/</Class-Path>
</manifestEntries>
</archive>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/*.yml</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<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-antrun-plugin</artifactId>
<version>1.8</version>
<dependencies>
<!-- 支持Ant条件判断 -->
<dependency>
<groupId>ant-contrib</groupId>
<artifactId>ant-contrib</artifactId>
<version>1.0b3</version>
<exclusions>
<exclusion>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-nodeps</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<taskdef resource="net/sf/antcontrib/antlib.xml"
classpathref="maven.plugin.classpath"/>
<if>
<equals arg1="${project.packaging}" arg2="jar"/>
<then>
<copy file="target/${project.artifactId}-${project.version}-bin.zip"
todir="${todir}"/>
</then>
<else>
<echo message="file suffix is not .zip, ignored. [file name:${project.artifactId}.${project.packaging}]"/>
</else>
</if>
<if>
<equals arg1="${project.packaging}" arg2="war"/>
<then>
<copy file="target/${project.artifactId}.${project.packaging}"
todir="${todir}"/>
</then>
<else>
<echo message="file suffix is not .war, ignored. [file name:${project.artifactId}.${project.packaging}]"/>
</else>
</if>
</target>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>dev/*</exclude>
<exclude>prod/*</exclude>
<exclude>test/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/${profiles.active}</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project> </project>
#!/bin/bash
#Current home
CURR_HOME=$(dirname $(readlink -f $0))
#jvm options
JAVA_OPTS="-Xms1g -Xmx1g -Djava.awt.headless=true -XX:MaxPermSize=512m -server -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=85 -Xnoclassgc -Xverify:none -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled"
JAR_FILE="$CURR_HOME/../${artifactId}-${version}.jar"
CMD="nohup java $JAVA_OPTS -jar $JAR_FILE > /dev/null 2>&1 &"
PID_FILE="${providers-path}/${artifactId}/run/${artifactId}-${profiles.active}.pid"
echo $JAR_FILE
###################################
#startup
###################################
start() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" != "" ] && [ -d "/proc/$pid" ]; then
echo "Process has been started with pid: $pid, ignore."
else
eval "$CMD"
pid=$!
echo "$pid" > "$PID_FILE"
echo "Process started at $pid."
fi
}
###################################
#stop
###################################
stop() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" == "" ] || [ ! -d "/proc/$pid" ]; then
echo "Process is not running, ignore."
else
echo "Trying to killing process $pid gracefully."
kill -15 $pid > /dev/null 2>&1
sleep 3
if [ -d "/proc/$pid" ]; then
echo "Process still alive, killing it in anger!"
kill -9 $pid > /dev/null 2>&1
fi
echo "Process stopped"
fi
if [ -f "$PID_FILE" ]; then
rm -f $PID_FILE
fi
}
###################################
#status
###################################
status() {
pid=""
if [ -f "$PID_FILE" ]; then
pid=`cat "$PID_FILE"`
fi
if [ "$pid" != "" ] && [ -d "/proc/$pid" ]; then
echo "Process is running! (pid=$pid)"
else
echo "Process is not running"
fi
}
###################################
###################################
#Accept only 1 argument:{start|stop|restart|status}
###################################
case "$1" in
'start')
start
;;
'stop')
stop
;;
'restart')
stop
start
;;
'status')
status
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit 0
package com.lanren.huhu.partner; package com.lanren.huhu.partner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author houseme
*/
@SpringBootApplication @SpringBootApplication
public class PartnerApplication { public class PartnerApplication {
public static void main(String[] args) { private static Logger logger = LoggerFactory.getLogger(PartnerApplication.class);
SpringApplication.run(PartnerApplication.class, args);
}
public static void main(String[] args) {
try {
SpringApplication.run(PartnerApplication.class, args);
logger.info("PartnerApplication >>>服务启动成功");
Object lock = new Object();
synchronized (lock) {
try {
while (true) {
lock.wait();
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
} catch (Exception e) {
logger.error("PartnerApplication>>服务启动失败", e);
e.printStackTrace();
}
}
} }
package com.lanren.huhu.partner.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author houseme
* @date 2017/9/8 上午11:54
* Project snacks
* Package com.yinguo.snacks.aspect
* File
*/
@Aspect
@Order(5)
@Component
public class WebLogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.yinguo.*.controller.*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
startTime.set(System.currentTimeMillis());
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
//header 部分处理
Map<String, String> map = new HashMap<String, String>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
logger.info("HEADER :{} ", map.toString());
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.JSON;
import com.lanren.huhu.partner.constants.CommonStatusConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* @author houseme
* @date 2019-04-02 21:31
* Project partner
* Package com.lanren.huhu.partner
* File: AuthenticationInterceptor
*/
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
private final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
HandlerMethod handlerMethod = (HandlerMethod) handler;
logger.info("AuthenticationInterceptor Method ==>{}", handlerMethod.getMethod().getName());
logger.info("AuthenticationInterceptor HandlerMethod ==>{}", handlerMethod.getBeanType().getName());
return true;
}
private void returnMsg(HttpServletResponse response) throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("code", CommonStatusConstant.SESSION_TIMEOUT.getValue());
map.put("msg", CommonStatusConstant.SESSION_TIMEOUT.getDesc());
response.setHeader("Content-type", "application/json;charset=UTF-8");
logger.info("msg :{}", CommonStatusConstant.SESSION_TIMEOUT.getDesc());
response.getWriter().write(JSON.toJSONString(map));
}
}
package com.lanren.huhu.partner.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
* @author houseme
* @date 2018/12/21
*/
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @author houseme
* @date 2018/1/22 下午11:51
* File
*/
@Configuration
@EnableCaching
public class RedisConfiguration {
@Bean
public RedisCacheManager getRedisCacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheWriter cacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer);
RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
return new RedisCacheManager(cacheWriter, cacheConfig);
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);
GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
//设置默认的Serialize,包含 keySerializer & valueSerializer
redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);
//单独设置valueSerializer
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
//单独设置keySerializer
redisTemplate.setKeySerializer(fastJsonRedisSerializer);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setStringSerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
package com.lanren.huhu.partner.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
/**
* @author houseme
* @date 2019-04-02 21:26
* Project xmb
* Package com.lanren.huhu.partner.config
* File: WebMvcAutoConfiguration
*/
@Configuration
@EnableWebMvc
public class WebMvcAutoConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/v1/**").excludePathPatterns("/v1/init/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
/**
* Configure cross origin requests processing.
*
* @param registry
* @since 4.2
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*").allowedMethods("POST", "GET", "PUT", "DELETE");
}
/**
* Configure the {@link HttpMessageConverter}s to use for reading or writing
* to the body of the request or response. If no converters are added, a
* default list of converters is registered.
* <p><strong>Note</strong> that adding converters to the list, turns off
* default converter registration. To simply add a converter without impacting
* default registration, consider using the method
* {@link #extendMessageConverters(List)} instead.
*
* @param converters initially an empty list of converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
supportedMediaTypes.add(MediaType.TEXT_PLAIN);
supportedMediaTypes.add(MediaType.TEXT_XML);
converter.setSupportedMediaTypes(supportedMediaTypes);
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
//config.set ...
SerializerFeature[] serializerFeatures = new SerializerFeature[]{
SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.QuoteFieldNames, SerializerFeature.WriteBigDecimalAsPlain
};
config.setSerializerFeatures(serializerFeatures);
converter.setFastJsonConfig(config);
converters.add(converter);
// ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
// objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
}
package com.lanren.huhu.partner.constants;
/**
* 改为枚举值定义
* 由于子项目的代码从10001开始,为避免重复,当前状态码应小于10000。
* MessageCodeLoader初始化时默认先加载当前枚举,然后加载msg.properties配置(实现继承关系:子项目不用再重复定义CommonStatus中已有的状态码)。
* 为避免子项目状态码重复,父类如已经定义,MessageCodeLoader不再加载子项目定义的冲突状态码(CommonStatus优先)。
*
* @author houseme
* @see com.yinguo.xmb.manager
* <p>
* <p>
* <p>
* 约定规则
* provider业务代码都应该在这里定义
* consumer业务代码在msg.properties定义
*/
public enum CommonStatusConstant {
OK(200, "成功!"),
CREATED(201, "已经创建!"),
DEFAULT_BIZ_ERROR(202, "业务异常!(此处应该被具体业务代码重写)"),
BAD_REQUEST(400, "请求失效,请稍后再试!"),
UNAUTHORIZED(401, "未经授权的操作,请联系系统管理员!"),
NOT_FOUND(404, "未找到资源,请稍后再试!"),
METHOD_NOT_ALLOWED(405, "该方法禁止调用,请联系系统管理员!"),
CONFLICT(409, "操作冲突,请稍后再试!"),
SESSION_TIMEOUT(410, "用户信息超时,请重新登录!"),
LOGIN_FAILD(411, "用户名或密码错误!"),
SESSION_REFRESH(412, "Token Refreshed"),
INVALID_PARAMETER(450, "参数验证未通过!"),
PERMISSION_DENIED(452, "权限拒绝,请联系系统管理员!"),
INTERNAL_SERVER_ERROR(500, "服务器内部异常,请稍后再试!"),
NO_REPLY(558, "服务器无应答,请稍后再试!!"),
UNCATCHED_EXCEPTION(553, "未捕获的异常,请稍后再试!"),
ENTITY_NOT_FOUNT(601, "数据未找到,请稍后再试!");
private Integer value;
private String desc;
private CommonStatusConstant(Integer value, String desc) {
this.value = value;
this.desc = desc;
}
public Integer getValue() {
return value;
}
public String getDesc() {
return desc;
}
}
package com.lanren.huhu.partner.manager;
import com.lanren.huhu.partner.constants.CommonStatusConstant;
import com.lanren.huhu.partner.util.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 初始化加载参数到内存中
* <p>
* 部分业务代码依赖CommonStatusConstant
*
* @author houseme
* @see com.lanren.huhu.partner.constants.CommonStatusConstant
*/
@Component
public class MessageCodeLoader {
private static Logger logger = LoggerFactory.getLogger(MessageCodeLoader.class);
public MessageCodeLoader() {
init("conf/msg.properties");
}
public MessageCodeLoader(String resource) {
init(resource);
}
public void init(String resource) {
try {
Properties p = new Properties();
p.load(this.getClass().getClassLoader().getResourceAsStream(resource));
Map<Integer, String> comm_code = toMap(CommonStatusConstant.class);
MessageUtil.putAll(comm_code);
for (Object obj : p.keySet()) {
MessageUtil.put(Integer.parseInt(obj.toString()), p.getProperty(obj.toString()));
}
} catch (IOException e) {
logger.error("init msg error", e);
}
}
public static void main(String[] args) {
MessageCodeLoader loader = new MessageCodeLoader();
loader.init("conf/msg.properties");
System.out.println(MessageUtil.getMsg(200));
}
public static Map<Integer, String> toMap(Class em) {
Map<Integer, String> map = new HashMap<>();
try {
Method m = em.getMethod("getValue");
Method m_ = em.getMethod("getDesc");
Object[] objs = em.getEnumConstants();
for (Object obj : objs) {
Integer k = (Integer) m.invoke(obj);
String v = (String) m_.invoke(obj);
map.put(k, v);
}
} catch (NoSuchMethodException e) {
logger.error("NoSuchMethodException.", e);
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException.", e);
} catch (Exception e) {
logger.error("Exception.", e);
}
return map;
}
}
package com.lanren.huhu.partner.result;
import com.lanren.huhu.partner.util.MessageUtil;
/**
* 封装Controller返回对象
*
* @author houseme
* @version 1.0
* @date 2016年7月18日 上午10:27:00
*/
public class Result<T> {
private int code;
private String message;
private T data;
private Long time;
public Result() {
this.code = 200;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public Result(T data) {
this.code = 200;
this.message = MessageUtil.getMsg(code);
this.data = data;
this.time = System.currentTimeMillis();
}
public Result(int code) {
this.code = code;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public Result(int code, String msg) {
this.code = code;
this.message = msg;
this.time = System.currentTimeMillis();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
this.message = MessageUtil.getMsg(code);
this.time = System.currentTimeMillis();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
@Override
public String toString() {
return "Result{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
", time=" + time +
'}';
}
}
# Created by .ignore support plugin (hsz.mobi)
package com.lanren.huhu.partner.service; package com.lanren.huhu.partner.service;
import java.util.List;
import com.lanren.huhu.partner.domain.PartnerAccount;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
public interface PartnerAccountService extends IService<PartnerAccount>{ import com.lanren.huhu.partner.domain.PartnerAccount;
import java.util.List;
/**
* @author houseme
*/
public interface PartnerAccountService extends IService<PartnerAccount> {
/**
* 批量更新
*
* @param list
* @return
*/
int updateBatch(List<PartnerAccount> list); int updateBatch(List<PartnerAccount> list);
/**
* 批量写入
*
* @param list
* @return
*/
int batchInsert(List<PartnerAccount> list); int batchInsert(List<PartnerAccount> list);
int insertOrUpdate(PartnerAccount record); /**
* 更新或新增
*
* @param partnerAccount
* @return
*/
int insertOrUpdate(PartnerAccount partnerAccount);
int insertOrUpdateSelective(PartnerAccount record); /**
* 选择性写入
*
* @param partnerAccount
* @return
*/
int insertOrUpdateSelective(PartnerAccount partnerAccount);
/***
* 根据用户id查询账户信息
* @param userId
* @return
*/
PartnerAccount getOneByUserId(Long userId);
} }
package com.lanren.huhu.partner.service.impl; package com.lanren.huhu.partner.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import com.lanren.huhu.partner.dao.PartnerAccountMapper; import com.lanren.huhu.partner.dao.PartnerAccountMapper;
import com.lanren.huhu.partner.domain.PartnerAccount; import com.lanren.huhu.partner.domain.PartnerAccount;
import com.lanren.huhu.partner.service.PartnerAccountService; import com.lanren.huhu.partner.service.PartnerAccountService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author houseme
*/
@Service @Service
public class PartnerAccountServiceImpl extends ServiceImpl<PartnerAccountMapper, PartnerAccount> implements PartnerAccountService{ public class PartnerAccountServiceImpl extends ServiceImpl<PartnerAccountMapper, PartnerAccount> implements PartnerAccountService {
@Override @Override
public int updateBatch(List<PartnerAccount> list) { public int updateBatch(List<PartnerAccount> list) {
return baseMapper.updateBatch(list); return baseMapper.updateBatch(list);
} }
@Override @Override
public int batchInsert(List<PartnerAccount> list) { public int batchInsert(List<PartnerAccount> list) {
return baseMapper.batchInsert(list); return baseMapper.batchInsert(list);
} }
@Override @Override
public int insertOrUpdate(PartnerAccount record) { public int insertOrUpdate(PartnerAccount record) {
return baseMapper.insertOrUpdate(record); return baseMapper.insertOrUpdate(record);
} }
@Override @Override
public int insertOrUpdateSelective(PartnerAccount record) { public int insertOrUpdateSelective(PartnerAccount record) {
return baseMapper.insertOrUpdateSelective(record); return baseMapper.insertOrUpdateSelective(record);
} }
public PartnerAccount getOne(Long userId){ @Override
public PartnerAccount getOneByUserId(Long userId) {
QueryWrapper<PartnerAccount> queryWrapper = new QueryWrapper(); QueryWrapper<PartnerAccount> queryWrapper = new QueryWrapper();
queryWrapper.eq("user_id", userId); queryWrapper.eq("user_id", userId);
baseMapper.selectCount(queryWrapper); return baseMapper.selectOne(queryWrapper);
return new PartnerAccount();
} }
} }
package com.lanren.huhu.partner.util;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 日期工具类
* <p>
* 默认使用 "yyyy-MM-dd HH:mm:ss" 格式化日期
*
* @author houseme
* @version1.0
*/
public final class DateUtils {
private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);
/**
* 英文简写(默认)如:2010-12-01
*/
public static String FORMAT_SHORT = "yyyy-MM-dd";
/**
* 英文最简写(默认)如:20101201
*/
public static String FORMAT_MORE_SHORT = "yyyyMMdd";
/**
* 英文全称 如:2010-12-01 23:15:06
*/
public static String FORMAT_LONG = "yyyy-MM-dd HH:mm:ss";
/**
* 英文全称 如:2010-12-01 23:15
*/
public static String FORMAT_CAR_DATE = "yyyy-MM-dd HH:mm";
/**
* 精确到毫秒的完整时间 如:yyyy-MM-dd HH:mm:ss.S
*/
public static String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.S";
/**
* 中文简写 如:2010年12月01日
*/
public static String FORMAT_SHORT_CN = "yyyy年MM月dd";
/**
* 中文全称 如:2010年12月01日 23时15分06秒
*/
public static String FORMAT_LONG_CN = "yyyy年MM月dd日 HH时mm分ss秒";
/**
* 精确到毫秒的完整中文时间 yyyy年MM月dd日 HH时mm分ss秒SSS毫秒
*/
public static String FORMAT_FULL_CN = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒";
/**
* 精确到秒的完整中文最简时间 yyyyMMddHHmmss
*/
public static String FORMAT_FULL_SIMPLE = "yyyyMMddHHmmss";
/**
* 精确到秒的完整中文最简时间 HHmmss 如:100101
*/
public static String FORMAT_TIME_FULL = "HHmmss";
/**
* 精确到毫秒的完整中文最简时间 如:20150304230516221
*/
public static String FORMAT_TIME_FULL_MILLI = "yyyyMMddHHmmssSSS";
/**
* 日期格式正则表达式
*/
public static String DATA_PATTERN = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
/**
* 短格式日期变长格式日期附加字符串,用于补充开始查询时间
*/
public static String ADDTIONAL_STR_BEGAIN = "2000-01-01 00:00:00";
/**
* 短格式日期变长格式日期附加字符串,用于补充结束查询时间
*/
public static String ADDTIONAL_STR_END = "2000-01-01 23:59:59";
/**
* 获得默认的 date pattern
*/
public static String getDatePattern() {
return FORMAT_LONG;
}
/**
* 获得默认的 date pattern
*/
public static String getCarDatePattern() {
return FORMAT_CAR_DATE;
}
/**
* <p>
* 功能描述:[方法功能中文描述]
* </p>
*
* @return
*/
public static Date getDate() {
return parse(getNow());
}
public static Date getDate(String format) {
return parse(getNow(), format);
}
/**
* 根据预设格式返回当前日期
*
* @return
*/
public static String getNow() {
return format(new Date());
}
/**
* 根据用户格式返回当前日期
*
* @param format
* @return
*/
public static String getNow(String format) {
return format(new Date(), format);
}
/**
* 使用预设格式格式化日期
*
* @param date
* @return
*/
public static String format(Date date) {
return format(date, getDatePattern());
}
/**
* 使用预设格式格式化日期
*
* @param date
* @return
*/
public static String carDateFormat(Date date) {
return format(date, getCarDatePattern());
}
/**
* 使用用户格式格式化日期
*
* @param date 日期
* @param pattern 日期格式
* @return
*/
public static String format(Date date, String pattern) {
String returnValue = "";
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
returnValue = df.format(date);
}
return (returnValue);
}
/**
* 使用预设格式提取字符串日期
*
* @param strDate 日期字符串
* @return
*/
public static Date parse(String strDate) {
return parse(strDate, getDatePattern());
}
/**
* 使用yyyy-MM-dd格式提取字符串日期
*
* @param strDate 日期字符串
* @return
*/
public static Date parseYMD(Date strDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return parse(dateFormat.format(strDate), "yyyy-MM-dd");
}
/**
* 使用预设格式提取字符串日期
*
* @param strDate 日期字符串
* @return
*/
public static Date parseDate(String strDate) {
return parse(strDate, getCarDatePattern());
}
/**
* 使用用户格式提取字符串日期
*
* @param strDate 日期字符串
* @param pattern 日期格式
* @return
*/
public static Date parse(String strDate, String pattern) {
if (StringUtil.isNullOrEmpty(strDate)) {
return null;
}
SimpleDateFormat df = new SimpleDateFormat(pattern);
try {
return df.parse(strDate);
} catch (ParseException e) {
return null;
}
}
/**
* 在日期上增加数个整月
*
* @param date 日期
* @param n 要增加的月数
* @return
*/
public static Date addMonth(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, n);
return cal.getTime();
}
/**
* 在日期上增加天数
*
* @param date 日期
* @param n 要增加的天数
* @return
*/
public static Date addDay(Date date, int n) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, n);
return cal.getTime();
}
public static String addDay(Date date, int i, String format) {
Date result = addDay(date, i);
return format(result, format);
}
/**
* 在当前日期上添加小时数
*
* @param date
* @param hour
* @return
*/
public static Date addHour(Date date, Double hour) {
Long time = date.getTime();
Double times = time + hour * 60 * 60 * 1000;
return new Date(Math.round(times));
}
public static Date subtractionHour(Date date, Double hour) {
Long time = date.getTime();
Double times = time - hour * 60 * 60 * 1000;
return new Date(Math.round(times));
}
/**
* 在当前日期上添加分钟数
*
* @param date
* @param mins
* @return
*/
public static Date addMinute(Date date, Double mins) {
Long time = date.getTime();
Double times = time + mins * 60 * 1000;
return new Date(Math.round(times));
}
/**
* 在当前日期上添加分钟数
*
* @param date
* @param mins
* @return
*/
public static Date addMinute(Date date, int mins) {
Long time = date.getTime();
Double times = time + Double.valueOf(mins) * 60 * 1000;
return new Date(Math.round(times));
}
/**
* 获取时间戳
*/
public static String getTimeString() {
SimpleDateFormat df = new SimpleDateFormat(FORMAT_FULL);
Calendar calendar = Calendar.getInstance();
return df.format(calendar.getTime());
}
/**
* 获取日期年份
*
* @param date 日期
* @return
*/
public static String getYear(Date date) {
return format(date).substring(0, 4);
}
/**
* 获取yyyy-MM-dd格式日期
*
* @param date
* @return
*/
public static String getShortDay(Date date) {
return format(date, FORMAT_SHORT);
}
/**
* 按默认格式的字符串距离今天的天数
*
* @param date 日期字符串
* @return
*/
public static int countDays(String date) {
long t = Calendar.getInstance().getTime().getTime();
Calendar c = Calendar.getInstance();
c.setTime(parse(date));
long t1 = c.getTime().getTime();
return (int) ((t / 1000 - t1 / 1000) / 3600 / 24);
}
/**
* 按用户格式字符串距离今天的天数
*
* @param date 日期字符串
* @param format 日期格式
* @return
*/
public static int countDays(String date, String format) {
long t = Calendar.getInstance().getTime().getTime();
Calendar c = Calendar.getInstance();
c.setTime(parse(date, format));
long t1 = c.getTime().getTime();
return (int) ((t / 1000 - t1 / 1000) / 3600 / 24);
}
/**
* 计算两个日期的间隔天数
*
* @return
*/
public static int countDays(Date start, Date end) {
long t1 = start.getTime();
long t2 = end.getTime();
return (int) ((t2 / 1000 - t1 / 1000) / 3600 / 24);
}
/**
* 计算两个日期格式为yyyy-MM-dd HH:mm:ss的月份数
*
* @param start
* @param end
* @return
*/
public static int countMonth(String start, String end) {
int month = 0;
int year = 0;
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(parse(start));
cal2.setTime(parse(end));
if (cal1.after(cal2)) {
Calendar temp = cal1;
cal1 = cal2;
cal2 = temp;
}
year = Math.abs(cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR));
month = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
return year * 12 + month;
}
/**
* 计算两个格式为yyyy-MM-dd日期的月份数
*
* @param start
* @param end
* @return
*/
public static int countMonth(Date start, Date end) {
int month = 0;
int year = 0;
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(start);
cal2.setTime(end);
if (cal1.after(cal2)) {
Calendar temp = cal1;
cal1 = cal2;
cal2 = temp;
}
year = Math.abs(cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR));
month = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
return year * 12 + month;
}
/**
* 忽略年份和月份,只计算天数
*
* @param start
* @param end
* @return
*/
public static int countDaysIngoreMonthAndYear(String start, String end) {
int result = 0;
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(DateUtils.parse(start));
cal2.setTime(DateUtils.parse(end));
result = cal2.get(Calendar.DATE) - cal1.get(Calendar.DATE);
return result;
}
/**
* 计算两个日期间隔天数
*
* @param start 开始日期
* @param end 结束日期
* @param isCeil 是否向上取整
*/
public static int countDays(Date start, Date end, boolean isCeil) {
if (!isCeil) {// 不满一天则不计算在内
return countDays(start, end);
}
int mins = countMins(start, end);
double hours = mins / 60.0 / 24;// 算出double类型的小时数
int intHours = (int) hours;
if (hours > intHours) {
intHours++;
}
return intHours;
}
/**
* 计算间隔小时数 -带半小时(不足半小时按照半小时 超过半小时按照一个小时算)
*
* @return
*/
public static double countHour(Date start, Date end) {
long t1 = start.getTime();
long t2 = end.getTime();
int hour = (int) ((t2 / 1000 - t1 / 1000) / 3600);
double halfHour = 0;
if ((countMins(start, end) - hour * 60) > 30) {
halfHour = 1;
} else if ((countMins(start, end) - hour * 60) <= 30 && (countMins(start, end) - hour * 60) > 0) {
halfHour = 0.5;
}
return hour + halfHour;
}
/**
* 计算两个日期的间隔分钟数
*
* @return
*/
public static int countMins(Date start, Date end) {
start = parse(format(start, FORMAT_CAR_DATE) + ":00", FORMAT_LONG);
end = parse(format(end, FORMAT_CAR_DATE) + ":00", FORMAT_LONG);
long t1 = start.getTime();
long t2 = end.getTime();
return (int) ((t2 - t1) / 1000 / 60);
}
/**
* 得到昨天0点
*/
public static Date getYester0Date() {
return parse(format(addDay(new Date(), -1), FORMAT_SHORT), FORMAT_SHORT);
}
/**
* 得到昨天24点
*/
public static Date getYester24Date() {
return parse(format(new Date(), FORMAT_SHORT), FORMAT_SHORT);
}
/**
* 判断是否是长短租
*
* @param startDate
* @param enDate
* @return
*/
public static boolean isMoreThenMonth(Date startDate, Date enDate) {
Calendar c = Calendar.getInstance();
c.setTime(startDate);
c.add(Calendar.MONTH, 1);
if (enDate.getTime() - c.getTimeInMillis() >= 0) {
return true;
} else {
return false;
}
}
/**
* 计算两个日期之间的时长
*
* @param startDate
* @param endDate
* @return
*/
public static String countDateLength(Date endDate, Date startDate) {
long diff = endDate.getTime() - startDate.getTime();
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
String hireTimeStr = days + "天" + hours + "小时" + minutes + "分";
return hireTimeStr;
}
public static String countDateLength(String endDate, String startDate, String pattern) {
return countDateLength(parse(endDate, pattern), parse(startDate, pattern));
}
/**
* 根据分钟得到小时数,不足一小时按一小时
*
* @param minute 分钟数
* @param isCeil 是否自动填满
* @return
*/
public static int countHours(int minute, boolean isCeil) {
int hours = 0;
if (minute == 0) {
return hours;
}
if (isCeil) {
if (minute % 60 == 0) {
hours = minute / 60;
} else {
hours = minute / 60 + 1;
}
} else {
hours = minute / 60;
}
return hours;
}
/**
* 根据分钟得到天数,不足一天按一天算
*
* @param minute 分钟数
* @return
*/
public static int countDays(int minute) {
int days = 0;
if (minute == 0) {
return days;
}
if (minute % 1440 == 0) {
days = minute / 1440;
} else {
days = minute / 1440 + 1;
}
return days;
}
/**
* 设置时间的秒为0
*
* @param date
* @return
*/
public static Date setSecondZero(Date date) {
String time = format(date, "yyyyMMddHHmm");
date = parse(time, "yyyyMMddHHmm");
return date;
}
/**
* 验证字符串是否为日期格式
*
* @param strDate
* @return
*/
public static boolean isDateFormat(String strDate) {
if (strDate == null) {
return Boolean.FALSE;
}
Pattern pattern = Pattern.compile(DATA_PATTERN);
Matcher matcher = pattern.matcher(strDate);
return matcher.matches();
}
/**
* 验证字符串是否为日期格式
*
* @param dateTime
* @return
*/
public static boolean isDateTimeFormat(String dateTime, String patternStr) {
if (StringUtil.isNullOrEmpty(dateTime) || StringUtil.isNullOrEmpty(patternStr)) {
return Boolean.FALSE;
}
SimpleDateFormat dfs = new SimpleDateFormat(patternStr);
try {
// 设置lenient为false.
// 否则SimpleDateFormat会比较宽松地验证日期,比如2007-02-29会被接受,并转换成2007-03-01
dfs.setLenient(false);
dfs.parse(dateTime);
return Boolean.TRUE;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return Boolean.FALSE;
}
}
/**
* 获取生成长格式日期字符串,用于日期型数据的查询条件
*
* @param strDate 日期格式字符串,支持yyyy-MM-dd、....、yyyy-MM-dd HH:mm:ss之时的格式
* @param additionalStr 用于补充strDate以满足 yyyy-MM-dd HH:mm:ss 格式<br/> 详见ADDTIONAL_STR_BEGAIN,ADDTIONAL_STR_END
* @return
*/
public static String getLongFormatDateStr(String strDate, String additionalStr) {
// 验证输入参数
if (strDate == null || strDate.trim().length() < 10 || additionalStr == null
|| additionalStr.trim().length() != 19) {
return null;
}
return strDate + additionalStr.substring(strDate.length());
}
/**
* 根据一个date时间 获取 day天前的日期 如:2016-6-17 HH:mm:ss 前30天 2016-5-18 HH:mm:ss
*
* @param d
* @param day
* @return
*/
public static Date getDateBefore(Date d, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - day);
return calendar.getTime();
}
/**
* 根据一个date时间 获取 day天后的日期 如:2016-5-18 HH:mm:ss 后30天 2016-6-17 HH:mm:ss
*
* @param d
* @param day
* @return
*/
public static Date getDateAfter(Date d, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(d);
calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + day);
return calendar.getTime();
}
/**
* 计算两个日期时间相差几天,几小时
*
* @param startTime 开始时间
* @param endTime 结束时间
* @param format 格式
* @param tag 比较返回的格式,D表示为天;H表示为小时,M表示为分钟,S表示为秒
* @return
*/
public static String dateDiff(String startTime, String endTime, String format, String tag) {
// 按照传入的格式生成一个simpledateformate对象
SimpleDateFormat sd = new SimpleDateFormat(format);
long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
long nh = 1000 * 60 * 60;// 一小时的毫秒数
long nm = 1000 * 60;// 一分钟的毫秒数
// 获得两个时间的毫秒时间差异
long diff = 0;
try {
diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
} catch (ParseException e) {
throw new RuntimeException();
}
long day = diff / nd;// 计算差多少天
long hour = diff % nd / nh;// 计算差多少小时
long min = diff % nd % nh / nm;// 计算差多少分钟
StringBuilder diffs = new StringBuilder();
if (day != 0) {
diffs.append(day + "天");
}
if (hour != 0) {
diffs.append(hour + "小时");
}
if (min != 0) {
diffs.append(min + "分钟");
}
return diffs.toString();
}
/**
* 两个时间点的时间差(秒)(目前微信使用)
*
* @return
* @throws ParseException
* @param: mintime 最小时间
* @param: maxtime 最大时间
*/
public static int diffSecond(String mintime, String maxtime) throws ParseException {
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date begin = dfs.parse(mintime);
Date end = dfs.parse(maxtime);
long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒
return new Long(between).intValue();
}
/**
* 时格式时间真是时间
*/
public static Date formatWorldTimeToGMTTime(String worldTime) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
return sdf.parse(worldTime);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 获取指定天的0:0:0
*
* @param day
* @return
*/
public static Date getYesterFastDate(Date day) {
Calendar cl = Calendar.getInstance();
cl.setTime(day);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MILLISECOND, 0);
return cl.getTime();
}
/**
* 获取指定天数的23:59:59
*
* @param day
* @return
*/
public static Date getYesterLastDate(Date day) {
Calendar cl = Calendar.getInstance();
cl.setTime(day);
cl.set(Calendar.HOUR_OF_DAY, 23);
cl.set(Calendar.MINUTE, 59);
cl.set(Calendar.SECOND, 59);
cl.set(Calendar.MILLISECOND, 999);
return cl.getTime();
}
// 默认时间格式
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//private static final String TIME_FORMAT = "HH:mm:ss";
/**
* 计算两个日期时间相差分钟
* @param dateTime1: yyyy-MM-dd HH:mm:ss
* @param dateTime2: yyyy-MM-dd HH:mm:ss
* @return
*/
public static long minuteBetween(String dateTime1, String dateTime2){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long diff = 0;
Date d1,d2;
try {
d1 = df.parse(dateTime1);
d2 = df.parse(dateTime2);
diff = (d1.getTime() - d2.getTime())/1000/60;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return diff;
}
/**
* 计算两个日期时间相差分钟
* @param dateTime1:
* @param dateTime2: yyyy-MM-dd HH:mm:ss
* @return
*/
public static long minuteBetween(Date dateTime1, Date dateTime2){
long diff = 0;
try {
diff = (dateTime1.getTime() - dateTime2.getTime())/1000/60;
} catch (Exception e) {
e.printStackTrace();
}
return diff;
}
/**
* 获取当前时间,默认 24小时制 "yyyy-MM-dd HH:mm:ss"
*/
public static String getCurrentTimeMillis() {
Date nowTime = new Date(System.currentTimeMillis());
SimpleDateFormat sdFormatter = new SimpleDateFormat(DATE_TIME_FORMAT);
String retStrFormatNowDate = sdFormatter.format(nowTime);
return retStrFormatNowDate;
}
/**
* 获取当前日期 yyyy-MM-dd
* @return
*/
public static String getToday(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String today = sdf.format(new Date());
return today;
}
/**
* 获取明天日期 yyyyMMdd 下一天
* @return
*/
public static String getTomorrow(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE, 1);
String tomorrow = sdf.format(calendar.getTime());
return tomorrow;
}
/**
* 将字符串yyyy-MM-dd转换为时间戳
* @param y_m_d
* @param hour
* @return
*/
public static long getZeroTimeByDateStr(String y_m_d, int hour) {
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Date date;
Calendar now = Calendar.getInstance();
try {
date = sdf.parse(y_m_d);
now.setTime(date);
now.set(Calendar.HOUR_OF_DAY, hour);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
} catch (ParseException e) {
e.printStackTrace();
}
return now.getTimeInMillis();
}
/**
* 将字符串yyyy-MM-dd转换为Date
* @param y_m_d
* @return
*/
public static Date getDateByDateStr(String y_m_d) {
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try {
date = sdf.parse(y_m_d);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String date2StringDate(java.sql.Date date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(date);
}
public static String date2StringDateNoLine(java.sql.Date date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyyMMdd");
return df.format(date);
}
public static String date2StringDatetime(java.sql.Date date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
public static String date2StringTime(java.sql.Date date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(date);
}
public static String timestamp2StringDate(Timestamp t) {
if (t == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(t);
}
public static String timestamp2StringTime(Timestamp t) {
if (t == null) {
return "";
}
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(t);
}
public static String timestamp2StringDatetime(Timestamp t) {
if (t == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(t);
}
public static String timestamp2StringDateHourMin(Timestamp t) {
if (t == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
return df.format(t);
}
public static java.sql.Date string2Date(String str) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return new java.sql.Date(df.parse(str).getTime());
}
public static java.sql.Date string2DateNoLine(String str) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
return new java.sql.Date(df.parse(str).getTime());
}
public static java.sql.Date string2Datetime(String str) {
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return new java.sql.Date(df.parse(str).getTime());
} catch (ParseException e) {
logger.error("日期格式化错误!", e);
throw new RuntimeException("日期格式化错误!");
}
}
public static java.sql.Date string2Time(String str) throws ParseException {
DateFormat df = new SimpleDateFormat("HH:mm:ss");
return new java.sql.Date(df.parse(str).getTime());
}
public static Timestamp string2Timestamp(String str) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date = df.parse(str);
String time = df.format(date);
return Timestamp.valueOf(time);
}
public static String date2StringMonthDate(java.sql.Date date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyyMM");
return df.format(date);
}
// T+1 非工作日
public static java.sql.Date periodStartTime(Integer period) {
Calendar time = Calendar.getInstance();
int day = time.get(Calendar.DAY_OF_YEAR);
time.set(Calendar.DAY_OF_YEAR, day + 1);
time.set(Calendar.MONTH, time.get(Calendar.MONTH) + period - 1);
return new java.sql.Date(time.getTime().getTime());
}
public static java.sql.Date periodEndTime(Integer period) {
Calendar time = Calendar.getInstance();
int day = time.get(Calendar.DAY_OF_YEAR);
time.set(Calendar.DAY_OF_YEAR, day + 1);
time.set(Calendar.MONTH, time.get(Calendar.MONTH) + period);
return new java.sql.Date(time.getTime().getTime());
}
public static String getCurrentDateTime(String formatType) {
java.util.Date date = new java.util.Date();
SimpleDateFormat sdf = new SimpleDateFormat(formatType);
return sdf.format(date);
}
/**
* 返回两个日期之间的天数,每月为30天,每年为360天
*
* @param start 开始日期
* @param end 结束日期
* @return 间隔的天数
*/
public static int getDateInterval(java.sql.Date start, java.sql.Date end) {
GregorianCalendar startCal = new GregorianCalendar();
GregorianCalendar endCal = new GregorianCalendar();
startCal.setTime(start);
endCal.setTime(end);
int startYear = startCal.get(Calendar.YEAR);
int endYear = endCal.get(Calendar.YEAR);
int startMonth = startCal.get(Calendar.MONTH);
int endMonth = endCal.get(Calendar.MONTH);
int months = 0;
if (startYear == endYear) {
months = endMonth - startMonth;
} else {
months = 12 * (endYear - startYear) + endMonth - startMonth;//两个日期相差几个月,即月份差
}
// months = months == 0 ? 0 : months - 1;
int startDay = startCal.get(Calendar.DATE) == 31 ? 30 : startCal.get(Calendar.DATE);
int endDay = endCal.get(Calendar.DATE) == 31 ? 30 : endCal.get(Calendar.DATE);
int gap = months * 30 + endDay - startDay;
return gap;
}
public static int dateDiff(String start, String end) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("zh", "cn"));
try {
long t1 = simpleDateFormat.parse(start).getTime();
long t2 = simpleDateFormat.parse(end).getTime();
int diff = (int) ((t2 - t1) / 1000);
return diff;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 两个时间相差距离多少分
*
* @param d1 时间参数 1
* @param d2 时间参数 2
* @return long 返回值为:分
*/
public static long getTimeIntervalInMinute(java.util.Date d1, java.util.Date d2) {
return Math.abs(d2.getTime() - d1.getTime()) / (1000 * 60);
}
public static boolean isValidDate(String str) {
String patternStr =
"^((((19|20)(([02468][048])|([13579][26]))\\-02\\-29))|((20[0-9][0-9])|(19[0-9][0-9]))\\-((((0[1-9])|(1[0-2]))\\-((0[1-9])|(1\\d)|(2[0-8])))|((((0[13578])|(1[02]))\\-31)|(((01,3-9])|(1[0-2]))\\-(29|30)))))$";
Pattern p = null;
Matcher m = null;
p = Pattern.compile(patternStr);
m = p.matcher(str);
boolean b = m.matches();
if (b) {
return true;
}else{
return false;
}
}
public static String dateDiffForTime(Long endTimeSec, Long startTimeSec) {
long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
long nh = 1000 * 60 * 60;//一小时的毫秒数
long nm = 1000 * 60;//一分钟的毫秒数
long ns = 1000;//一秒钟的毫秒数
long diff;
long day = 0L;//计算差多少天
long hour = 0L;//计算差多少小时
long min = 0L;//计算差多少分钟
long sec = 0L;//计算差多少秒
StringBuffer result = new StringBuffer();
//获得两个时间的毫秒时间差异
diff = endTimeSec - startTimeSec;
if (diff >= 0) {
day = diff / nd;//计算差多少天
hour = diff % nd / nh;//计算差多少小时
min = diff % nd % nh / nm;//计算差多少分钟
sec = diff % nd % nh % nm / ns;//计算差多少秒
result.append(day + "天");
if (hour < 10) {
result.append("0" + hour + "小时");
} else {
result.append(hour + "小时");
}
if (min < 10) {
result.append("0" + min + "分");
} else {
result.append(min + "分");
}
if (sec < 10) {
result.append("0" + sec + "秒");
} else {
result.append(sec + "秒");
}
} else {
result.append("0天00小时00分00秒");
}
//输出结果
return result.toString();
}
public static String dateDiffForTimeValue(Long endTimeSec, Long startTimeSec) {
long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
long nh = 1000 * 60 * 60;//一小时的毫秒数
long nm = 1000 * 60;//一分钟的毫秒数
long ns = 1000;//一秒钟的毫秒数
long diff;
long day = 0L;//计算差多少天
long hour = 0L;//计算差多少小时
long min = 0L;//计算差多少分钟
long sec = 0L;//计算差多少秒
StringBuffer result = new StringBuffer();
//获得两个时间的毫秒时间差异
diff = endTimeSec - startTimeSec;
if (diff >= 0) {
day = diff / nd;//计算差多少天
hour = diff % nd / nh;//计算差多少小时
min = diff % nd % nh / nm;//计算差多少分钟
sec = diff % nd % nh % nm / ns;//计算差多少秒
result.append(day + ":");
result.append(hour + ":");
result.append(min + ":");
result.append(sec);
} else {
result.append("0:0:0:0");
}
//输出结果
return result.toString();
}
public static String dateDiffForUsedTime(Long endTimeSec, Long startTimeSec) {
long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
long nh = 1000 * 60 * 60;//一小时的毫秒数
long nm = 1000 * 60;//一分钟的毫秒数
long ns = 1000;//一秒钟的毫秒数
long diff;
long day = 0L;//计算差多少天
long hour = 0L;//计算差多少小时
long min = 0L;//计算差多少分钟
long sec = 0L;//计算差多少秒
StringBuffer result = new StringBuffer();
//获得两个时间的毫秒时间差异
diff = endTimeSec - startTimeSec;
if (diff >= 0) {
day = diff / nd;//计算差多少天
hour = diff % nd / nh;//计算差多少小时
min = diff % nd % nh / nm;//计算差多少分钟
sec = diff % nd % nh % nm / ns;//计算差多少秒
if (day > 0) {
result.append(day + "天");
}
if (hour > 0) {
result.append(hour + "小时");
}
if (min > 0) {
result.append(min + "分");
}
if (sec > 0) {
result.append(sec + "秒");
}
}
//输出结果
return result.toString();
}
public static String millisecondsToTime(long milliseconds) {
long nd = 1000 * 24 * 60 * 60;//一天的毫秒数
long nh = 1000 * 60 * 60;//一小时的毫秒数
long nm = 1000 * 60;//一分钟的毫秒数
long ns = 1000;//一秒钟的毫秒数
long day = 0L;//计算差多少天
long hour = 0L;//计算差多少小时
long min = 0L;//计算差多少分钟
long sec = 0L;//计算差多少秒
day = milliseconds / nd;//计算差多少天
hour = milliseconds % nd / nh;//计算差多少小时
min = milliseconds % nd % nh / nm;//计算差多少分钟
sec = milliseconds % nd % nh % nm / ns;//计算差多少秒
return String.format("%02d天%02d时%02d分%02d秒", day, hour, min, sec);
}
public static int compareDate(String startDate, String endDate, String formatter) {
int compareResult = 0;
DateFormat dateFormat = new SimpleDateFormat(formatter);
try {
java.util.Date dateTime1 = dateFormat.parse(startDate);
java.util.Date dateTime2 = dateFormat.parse(endDate);
compareResult = dateTime1.compareTo(dateTime2);
} catch (Exception e) {
e.printStackTrace();
}
return compareResult;
}
public static java.sql.Date addDay(java.sql.Date date, int dayNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, dayNum);// 把日期往后增加dayNum天,整数往后推,负数往前移动
return new java.sql.Date(calendar.getTime().getTime());
}
public static java.sql.Date addSecond(java.sql.Date date, int secNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, secNum);// 把日期往后增加secNum秒,整数往后推,负数往前移动
return new java.sql.Date(calendar.getTime().getTime());
}
public static String getChDateMD(String date) throws Exception {
StringBuffer out = new StringBuffer("");
Calendar calendar = Calendar.getInstance();
calendar.setTime(string2Date(date));
out.append((calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DATE) + "日");
return out.toString();
}
public static String getChDateMD(java.sql.Date date) {
StringBuffer out = new StringBuffer("");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
out.append((calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DATE) + "日");
return out.toString();
}
public static String getChDateYMD(String date) throws Exception {
StringBuffer out = new StringBuffer("");
Calendar calendar = Calendar.getInstance();
calendar.setTime(string2Date(date));
out.append(calendar.get(Calendar.YEAR) + " 年 " + (calendar.get(Calendar.MONTH) + 1) + " 月 " + calendar.get(Calendar.DATE) + " 日 ");
return out.toString();
}
public static String getChDateYMD(java.sql.Date date) throws Exception {
StringBuffer out = new StringBuffer("");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
out.append(calendar.get(Calendar.YEAR) + " 年 " + (calendar.get(Calendar.MONTH) + 1) + " 月 " + calendar.get(Calendar.DATE) + " 日 ");
return out.toString();
}
public static int getWeekDay(java.sql.Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}
public static int getHour(java.sql.Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal.get(Calendar.HOUR_OF_DAY);
}
public static String date2StringDateTimeNoLine(Timestamp date) {
if (date == null) {
return "";
}
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
return df.format(date);
}
/**
* 增添天数的23.59.59S
*
* @param date
* @param dayNum
* @return
* @throws ParseException
*/
public static java.util.Date addDayHms(java.util.Date date, int dayNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, dayNum);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
return calendar.getTime();
}
/**
* 获取下一个纪念日
* @param commemorationDay “yyyy-MM-dd”
* @return yyyy-MM-dd
*/
public static String nextCommemorationDay(String commemorationDay) {
SimpleDateFormat myFormatter = new SimpleDateFormat(FORMAT_SHORT);
Calendar cToday = Calendar.getInstance(); // 存今天
Calendar cBirth = Calendar.getInstance(); // 存纪念日
Calendar nextBirthDay = Calendar.getInstance(); //存下一个纪念日
try {
cBirth.setTime(myFormatter.parse(commemorationDay)); // 设置纪念日
} catch (ParseException e) {
e.printStackTrace();
}
int month = cBirth.get(Calendar.MONTH);
int day = cBirth.get(Calendar.DAY_OF_MONTH);
// int currentYear = cToday.get(Calendar.YEAR);
// System.out.println("currentYear:"+currentYear+" month:"+month+" day:"+day);
if(month==1 && day==29){
int curYear = cToday.get(Calendar.YEAR);
int v = curYear%4;
int nextCYear = curYear+4-v;
if(v==0){ //当前年就是闰年
nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年纪念日
nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年纪念日
if(nextBirthDay.before(cToday)){ //今年生日已过
nextBirthDay.set(Calendar.YEAR,nextCYear);
}
}else{ // 当年不是闰年
nextBirthDay.set(Calendar.YEAR,nextCYear);
nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年纪念日
nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年纪念日
}
}else {
nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年纪念日
nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年纪念日
if(nextBirthDay.before(cToday)){ //今年纪念日已过
nextBirthDay.add(Calendar.YEAR,1);
}
}
return myFormatter.format(nextBirthDay.getTime());
}
/*
* 将时间转换为时间戳
*/
public static int dateToStamp(String dt){
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = simpleDateFormat.parse(dt);
} catch (ParseException e) {
e.printStackTrace();
}
int ts = (int)(date.getTime()/1000);
return ts;
}
public static void main(String[] args) throws ParseException {
//--------------------------------------------------------------------------------
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//
// Date d1 = parse("2019-05-23 23:00:01","yyyy-MM-dd");
// Date d2 = new Date(); // parse("2019-05-18 06:00:00","yyyy-MM-dd");
//
//// String d2_str = dateFormat.format(d2);
//// String d1_str = dateFormat.format(d1);
////
//// Date d1New = parse(d1_str,"yyyy-MM-dd");
//// Date d2New = parse(d2_str,"yyyy-MM-dd");
//
//
// Date d1New = parseYMD(d1);
// Date d2New = parseYMD(d2);
//
//
// System.out.println(d2New.compareTo(d1New));
//--------------------------------------------------------------------------
// SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
// String clidate = "1996-02-29";
// Calendar cToday = Calendar.getInstance(); // 存今天
// Calendar cBirth = Calendar.getInstance(); // 存生日
// Calendar nextBirthDay = Calendar.getInstance(); //存未来生日
// cBirth.setTime(myFormatter.parse(clidate)); // 设置生日
//
// int month = cBirth.get(Calendar.MONTH);
// int day = cBirth.get(Calendar.DAY_OF_MONTH);
//
// int currentYear = cToday.get(Calendar.YEAR);
// System.out.println("currentYear:"+currentYear+" month:"+month+" day:"+day);
//
// if(month==1 && day==29){
// System.out.println("1--->1");
// int curYear = cToday.get(Calendar.YEAR);
// int v = curYear%4;
//
// int nextCYear = curYear+4-v;
//
// if(v==0){ //当前年就是闰年
// System.out.println("1--->2");
// nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年生日
// nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年生日
// if(nextBirthDay.before(cToday)){ //今年生日已过
// nextBirthDay.set(Calendar.YEAR,nextCYear);
// }
//
// }else{ // 当年不是闰年
// System.out.println("1--->3");
// nextBirthDay.set(Calendar.YEAR,nextCYear);
// nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年生日
// nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年生日
// }
//
// }else {
// System.out.println("2--->1");
// nextBirthDay.set(Calendar.MONTH, cBirth.get(Calendar.MONTH)); // will修改为本年生日
// nextBirthDay.set(Calendar.DAY_OF_MONTH, cBirth.get(Calendar.DAY_OF_MONTH)); // will修改为本年生日
// if(nextBirthDay.before(cToday)){ //今年生日已过
// System.out.println("2--->2");
// nextBirthDay.add(Calendar.YEAR,1);
// }
// }
//
// System.out.println("today: "+myFormatter.format(cToday.getTime()));
// System.out.println("birth: "+myFormatter.format(cBirth.getTime()));
// System.out.println("nextBirthday: "+myFormatter.format(nextBirthDay.getTime()));
String day = "2019-05-24";
String result = nextCommemorationDay(day);
System.out.println(result);
// Time time = new Time(12,25,30);
//
// String timeStr = time.toString();
//
// System.out.println(timeStr);
}
}
package com.lanren.huhu.partner.util;
import org.springframework.util.StringUtils;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
/**
* @author houseme
*/
public class MessageUtil {
private static Map<Integer, String> cache = new HashMap<Integer, String>();
public static void put(int code, String msg) {
if (cache.containsKey(code)) {
return;
}
cache.put(code, msg);
}
public static void putAll(Map<Integer, String> map) {
cache.putAll(map);
}
public static String getMsg(int code) {
return getMsg(code, "");
}
public static String getMsg(int code, String defaultValue) {
return getMsg(code, null, defaultValue);
}
public static String getMsg(int code, String[] params, String defaultValue) {
return cache.containsKey(code) ? handleParam(cache.get(code), params) : defaultValue;
}
protected static String handleParam(String msg, String[] params) {
if (params == null || params.length == 0) {
return msg;
}
if (StringUtils.isEmpty(msg)) {
return "";
}
MessageFormat mf = new MessageFormat(msg);
mf.setLocale(Locale.CHINESE);
return mf.format(params);
}
}
spring: spring:
datasource: datasource:
#连接MySQL #连接MySQL
url: jdbc:mysql://localhost:3306/socks?useSSL=false url: @mysql.server@?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&allowMultiQueries=true
username: root username: @mysql.username@
password: root password: @mysql.password@
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
max-active: 10
min-idle: 5
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
max-open-prepared-statements: 20
validation-query: SELECT 1
validation-query-timeout: 1200000
test-on-borrow: false
test-on-return: false
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
max-evictable-idle-time-millis: 900000
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000;keepAlive=true
filters: stat,wall,slf4j
aop-patterns: com.lanren.huhu.partner.service.*
# # 配置StatFilter
filter.stat.db-type: mysql
filter.stat.log-slow-sql: true
filter.stat.slow-sql-millis: 2000
# 配置WallFilter
filter.wall.enabled: true
filter.wall.db-type: mysql
filter.wall.config.delete-allow: true
filter.wall.config.truncate-allow: false
filter.wall.config.drop-table-allow: false
filter.slf4j.enabled: true
filter.slf4j.statement-create-after-log-enabled: false
filter.slf4j.statement-close-after-log-enabled: false
filter.slf4j.result-set-open-after-log-enabled: false
filter.slf4j.result-set-close-after-log-enabled: false
profiles:
active: @profiles.active@
jmx:
default-domain: @project.artifactId@
## Redis 配置
## Redis数据库索引(默认为0)
redis:
database: 12
## Redis测试服务器地址
host: @redis.host@
## Redis测试服务器连接端口
port: 6379
## Redis测试服务器连接密码(默认为空)
password: @redis.password@
## 连接池最大连接数(使用负值表示没有限制)
lettuce:
pool:
max-active: 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
## 连接池中的最大空闲连接
max-idle: 8
## 连接池中的最小空闲连接
min-idle: 0
shutdown-timeout: 100ms
## 连接超时时间(毫秒)
timeout: 5000ms
http:
encoding:
charset: UTF-8
enabled: true
force: true
converters:
preferred-json-mapper: fastjson
server:
port: 8099
http2:
enabled: true
tomcat:
uri-encoding: UTF-8
mybatis: mybatis:
configuration: configuration:
#配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。 #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
mybatis-plus:
type-aliases-package: com.lanren.huhu.partner.domain
mapper-locations: classpath:mapper/*.xml
logging: logging:
level: level:
#打印SQL信息 #打印SQL信息
com.hehe.mapper: debug com.hehe.mapper: debug
200=\u6210\u529F
201=\u5DF2\u7ECF\u521B\u5EFA
202=\u4E1A\u52A1\u5F02\u5E38\uFF01\uFF08\u6B64\u5904\u5E94\u8BE5\u88AB\u5177\u4F53\u4E1A\u52A1\u4EE3\u7801\u91CD\u5199\uFF09
400=\u8BF7\u6C42\u5931\u6548\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
401=\u672A\u7ECF\u6388\u6743\u7684\u64CD\u4F5C\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
404=\u672A\u627E\u5230\u8D44\u6E90\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
405=\u8BE5\u65B9\u6CD5\u7981\u6B62\u8C03\u7528\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
409=\u64CD\u4F5C\u51B2\u7A81\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
410=\u7528\u6237\u4FE1\u606F\u8D85\u65F6\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\uFF01
411=\u7528\u6237\u540D\u6216\u5BC6\u7801\u9519\u8BEF\uFF01
413=\u7528\u6237\u4FE1\u606F\u5F02\u5E38\uFF01
450=\u53C2\u6570\u9A8C\u8BC1\u672A\u901A\u8FC7\uFF01
452=\u6743\u9650\u62D2\u7EDD\uFF0C\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\uFF01
500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
558=\u670D\u52A1\u5668\u65E0\u5E94\u7B54\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01\uFF01
553=\u672A\u6355\u83B7\u7684\u5F02\u5E38\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
601=\u6570\u636E\u672A\u627E\u5230\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\uFF01
60404=\u6682\u65E0\u6570\u636E\uFF01
#\u767B\u5F55\u76F8\u5173
10100=\u8BF7\u9009\u62E9\u6B63\u786E\u7684\u767B\u5F55\u65B9\u5F0F
10101=\u6388\u6743\u767B\u5F55\u5931\u8D25
10102=\u6388\u6743\u767B\u5F55\u5931\u8D25,\u8BF7\u91CD\u65B0\u6388\u6743
10201=\u767B\u5F55\u6765\u6E90\u6682\u4E0D\u652F\u6301
#OpenId \u672A\u7ED1\u5B9A
10202=\u672A\u7ED1\u5B9A
10203=\u7528\u6237\u5DF2\u7ED1\u5B9A\u4E86\u5176\u4ED6\u7684OPENID
#\u8BE5\u624B\u673A\u53F7\u672A\u627E\u5230\u7528\u6237\u4FE1\u606F
10401=\u624B\u673A\u53F7\u7801\u672A\u6CE8\u518C
10402=\u5BC6\u7801\u9519\u8BEF
#\u7528\u6237\u5DF2\u8FDB\u5165\u5C0F\u9ED1\u5C4B
10403=\u7528\u6237\u5DF2\u7981\u7528
#\u8BE5\u624B\u673A\u53F7\u5728\u7CFB\u7EDF\u4E2D\u5DF2\u5B58
10404=\u624B\u673A\u53F7\u7801\u5DF2\u6CE8\u518C
10405=\u624B\u673A\u53F7\u7801\u586B\u5199\u9519\u8BEF
#\u5BC6\u7801\u9700\u5927\u4E8E\u516D\u4F4D
10406=\u5BC6\u7801\u81F3\u5C11\u516D\u4F4D
10407=\u627E\u56DE\u5BC6\u7801\u5931\u8D25
#OpenID \u5DF2\u88AB\u7ED1\u5B9A
10408=\u5FAE\u4FE1\u5DF2\u88AB\u7ED1\u5B9A
#OpenID\u4E0D\u5B58\u5728
10409=\u672A\u7ED1\u5B9A
10410=\u8BF7\u5148\u901A\u8FC7\u627E\u56DE\u5BC6\u7801\u8BBE\u7F6E\u5BC6\u7801
10600=\u53C2\u6570\u4E3A\u7A7A
10601=\u624B\u673A\u53F7\u6216\u5BC6\u7801\u4E3A\u7A7A
10602=\u9A8C\u8BC1\u7801\u4E3A\u7A7A
10603=\u9A8C\u8BC1\u7801\u9519\u8BEF
10801=\u9875\u6570\u9519\u8BEF
10802=\u6BCF\u9875\u6761\u6570\u9519\u8BEF
#ReckonTime \u9519\u8BEF\u4EE3\u7801\uFF08109\u5F00\u5934\uFF09
10900=\u4E8B\u4EF6\u5361id\u9519\u8BEF
10901=\u7528\u6237id\u4E0D\u80FD\u4E3A\u7A7A
10902=\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A
10903=\u7C7B\u522Bid\u9519\u8BEF
10904=\u8BA1\u65F6\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A
10905=\u76EE\u6807\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A
10906=\u63D0\u9192\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A
10907=\u63D0\u9192\u53C2\u6570\u4E0D\u80FD\u4E3A\u7A7A
10908=\u7C7B\u522B\u7EC4\u9519\u8BEF
10909=\u5931\u8D25
10910=\u65E5\u671F\u5FC5\u987B\u5C0F\u4E8E\u5F53\u65E5
10911=\u7F6E\u9876\u53C2\u6570\u9519\u8BEF
10912=\u80CC\u666F\u989C\u8272id\u9519\u8BEF
10913=\u5B57\u4F53\u989C\u8272id\u9519\u8BEF
10914=\u91CD\u590D\u5FAA\u73AF\u53C2\u6570\u9519\u8BEF
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<property name="pattern" value="[%level] %d{yy-MM-dd HH:mm:ss.SSS} [%thread] %logger{50}:%line - %msg%n"/>
<property name="log_file" value="@logfile_path@/@profiles.active@/@artifactId@-@profiles.active@"/>
<property name="MaxHistory" value="15"/><!--日志保留天数-->
<property name="MaxFileSize" value="1024MB"/><!--单个文件大小-->
<property name="totalSizeCap" value="1024MB"/><!--单个文件大小-->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
</appender>
<appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log_file}-info.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${log_file}-info.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<MaxHistory>${MaxHistory}</MaxHistory>
<MaxFileSize>${MaxFileSize}</MaxFileSize>
<totalSizeCap>${totalSizeCap}</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
</appender>
<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log_file}-error.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<FileNamePattern>${log_file}-error.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<MaxHistory>${MaxHistory}</MaxHistory>
<MaxFileSize>${MaxFileSize}</MaxFileSize>
<totalSizeCap>${totalSizeCap}</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<root level="info">
<appender-ref ref="stdout"/>
<appender-ref ref="info"/>
<appender-ref ref="error"/>
</root>
</configuration>
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 to comment