aa72ced8 by 蔡永松

Minio服务集成

1 parent 6b9b1868
......@@ -366,7 +366,7 @@
</profiles>
<properties>
<oracle.version>11.2.0.4</oracle.version>
<oracle.version>11.2.0.3</oracle.version>
<geotools.version>24-SNAPSHOT</geotools.version>
<org.springframework.version>5.1.8.RELEASE</org.springframework.version>
<org.spring.boot.version>2.1.8.RELEASE</org.spring.boot.version>
......
package com.pashanhoo.common.minio;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
public class DateUtils {
//获取当天的开始时间
public static Date getDayBegin() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
//获取当天的结束时间
public static Date getDayEnd() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
//获取昨天的开始时间
public static Date getBeginDayOfYesterday() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
//获取昨天的结束时间
public static Date getEndDayOfYesterDay() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
//获取明天的开始时间
public static Date getBeginDayOfTomorrow() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
//获取明天的结束时间
public static Date getEndDayOfTomorrow() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
//获取本周的开始时间
@SuppressWarnings("unused")
public static Date getBeginDayOfWeek() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek);
return getDayStartTime(cal.getTime());
}
//获取本周的结束时间
public static Date getEndDayOfWeek(){
Calendar cal = Calendar.getInstance();
cal.setTime(getBeginDayOfWeek());
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
return getDayEndTime(weekEndSta);
}
//获取上周的开始时间
@SuppressWarnings("unused")
public static Date getBeginDayOfLastWeek() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek - 7);
return getDayStartTime(cal.getTime());
}
//获取上周的结束时间
public static Date getEndDayOfLastWeek(){
Calendar cal = Calendar.getInstance();
cal.setTime(getBeginDayOfLastWeek());
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
return getDayEndTime(weekEndSta);
}
//获取本月的开始时间
public static Date getBeginDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 1, 1);
return getDayStartTime(calendar.getTime());
}
//获取本月的结束时间
public static Date getEndDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 1, 1);
int day = calendar.getActualMaximum(5);
calendar.set(getNowYear(), getNowMonth() - 1, day);
return getDayEndTime(calendar.getTime());
}
//获取上月的开始时间
public static Date getBeginDayOfLastMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 2, 1);
return getDayStartTime(calendar.getTime());
}
//获取上月的结束时间
public static Date getEndDayOfLastMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 2, 1);
int day = calendar.getActualMaximum(5);
calendar.set(getNowYear(), getNowMonth() - 2, day);
return getDayEndTime(calendar.getTime());
}
//获取本年的开始时间
public static Date getBeginDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
// cal.set
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 1);
return getDayStartTime(cal.getTime());
}
//获取本年的结束时间
public static Date getEndDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.DATE, 31);
return getDayEndTime(cal.getTime());
}
//获取某个日期的开始时间
public static Date getDayStartTime(Date d) {
Calendar calendar = Calendar.getInstance();
if(null != d) calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
//获取某个日期的结束时间
public static Date getDayEndTime(Date d) {
Calendar calendar = Calendar.getInstance();
if(null != d) calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
//获取今年是哪一年
public static Integer getNowYear() {
Date date = new Date();
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
return Integer.valueOf(gc.get(1));
}
//获取本月是哪一月
public static int getNowMonth() {
Date date = new Date();
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
return gc.get(2) + 1;
}
//两个日期相减得到的天数
public static int getDiffDays(Date beginDate, Date endDate) {
if (beginDate == null || endDate == null) {
throw new IllegalArgumentException("getDiffDays param is null!");
}
long diff = (endDate.getTime() - beginDate.getTime())
/ (1000 * 60 * 60 * 24);
int days = new Long(diff).intValue();
return days;
}
//两个日期相减得到的毫秒数
public static long dateDiff(Date beginDate, Date endDate) {
long date1ms = beginDate.getTime();
long date2ms = endDate.getTime();
return date2ms - date1ms;
}
//获取两个日期中的最大日期
public static Date max(Date beginDate, Date endDate) {
if (beginDate == null) {
return endDate;
}
if (endDate == null) {
return beginDate;
}
if (beginDate.after(endDate)) {
return beginDate;
}
return endDate;
}
public static final String DATEFORMAT = "yyyyMMdd";
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String DATA_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 日期转换为"yyyy-MM-dd"格式字符串
*
* @param date 需要转换的日期
* @return String 转换后的日期串
*/
public static String dateToStr(Date date) {
DateFormat df = new SimpleDateFormat(DATEFORMAT);
return df.format(date);
}
/**
* 日期转换为"yyyy-MM-dd"格式字符串
*
* @param date 需要转换的日期
* @return String 转换后的日期串
*/
public static String dateToString(Date date) {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
return df.format(date);
}
/**
* 日期转换为"yyyy-MM-dd HH:mm:ss"格式字符串
*
* @param date
* 需要转换的日期
* @return 转换后的日期串
*/
public static String dateToStringAll(Date date) {
DateFormat df = new SimpleDateFormat(DATA_TIME_FORMAT);
return df.format(date);
}
//获取两个日期中的最小日期
public static Date min(Date beginDate, Date endDate) {
if (beginDate == null) {
return endDate;
}
if (endDate == null) {
return beginDate;
}
if (beginDate.after(endDate)) {
return endDate;
}
return beginDate;
}
//返回某月该季度的第一个月
public static Date getFirstSeasonDate(Date date) {
final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int sean = SEASON[cal.get(Calendar.MONTH)];
cal.set(Calendar.MONTH, sean * 3 - 3);
return cal.getTime();
}
//返回某个日期下几天的日期
public static Date getNextDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return cal.getTime();
}
//返回某个日期前几天的日期
public static Date getFrontDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
return cal.getTime();
}
//获取某年某月到某年某月按天的切片日期集合(间隔天数的集合)
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List getTimeList(int beginYear, int beginMonth, int endYear,
int endMonth, int k) {
List list = new ArrayList();
if (beginYear == endYear) {
for (int j = beginMonth; j <= endMonth; j++) {
list.add(getTimeList(beginYear, j, k));
}
} else {
{
for (int j = beginMonth; j < 12; j++) {
list.add(getTimeList(beginYear, j, k));
}
for (int i = beginYear + 1; i < endYear; i++) {
for (int j = 0; j < 12; j++) {
list.add(getTimeList(i, j, k));
}
}
for (int j = 0; j <= endMonth; j++) {
list.add(getTimeList(endYear, j, k));
}
}
}
return list;
}
//获取某年某月按天切片日期集合(某个月间隔多少天的日期集合)
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List getTimeList(int beginYear, int beginMonth, int k) {
List list = new ArrayList();
Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
int max = begincal.getActualMaximum(Calendar.DATE);
for (int i = 1; i < max; i = i + k) {
list.add(begincal.getTime());
begincal.add(Calendar.DATE, k);
}
begincal = new GregorianCalendar(beginYear, beginMonth, max);
list.add(begincal.getTime());
return list;
}
//给当前时间加上min分钟
public static Date getNewDate(Date cur,Integer min ) {
Calendar c = Calendar.getInstance();
c.setTime(cur); //设置时间
c.add(Calendar.MINUTE, min); //日期分钟加30,Calendar.DATE(天),Calendar.HOUR(小时)
Date date = c.getTime(); //结果
return date;
}
/**
* 时间格式(yyyy-MM-dd)
*/
public final static String DATE_PATTERN = "yyyy-MM-dd";
/**
* 时间格式(yyyy-MM-dd HH:mm:ss)
*/
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
/**
* 比较两个字符串时间大小
*/
public static int compareTwoTime(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
int flagValue = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
long millisecond = date1.getTime() - date2.getTime();
if (millisecond > 0) {
flagValue = 1;
} else if (millisecond < 0) {
flagValue = -1;
} else if (millisecond == 0) {
flagValue = 0;
}
} catch (ParseException e) {
e.printStackTrace();
}
return (flagValue);
}
/**
* 比较两个时间差
* time1>time2=1
* time1<time2=-1
* time1=time2=0
*
* @param time1
* @param time2
* @return
*/
public static int compareTwoTime(Date time1, Date time2) {
int flagValue = 0;
try {
long millisecond = time1.getTime() - time2.getTime();
if (millisecond > 0) {
flagValue = 1;
} else if (millisecond < 0) {
flagValue = -1;
} else if (millisecond == 0) {
flagValue = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return (flagValue);
}
/**
* 比较两个时间相差天数
*/
public static float calculateTimeGapDay(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
float day = 0;
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
long millisecond = date2.getTime() - date1.getTime();
day = millisecond / (24 * 60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return (day);
}
/**
* 比较两个时间相差天数
*/
public static float calculateTimeGapDay(Date time1, Date time2) {
float day = 0;
try {
Date date1, date2;
date1 = time1;
date2 = time2;
long millisecond = date2.getTime() - date1.getTime();
day = millisecond / (24 * 60 * 60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
return (day);
}
/**
* 比较两个时间相差小时
*/
public static double calculatetimeGapHour(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
double hour = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
hour = millisecond / (60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return hour;
}
/**
* 比较两个时间相差小时
*/
public static double calculatetimeGapHour(Date date1, Date date2) {
double hour = 0;
double millisecond = date2.getTime() - date1.getTime();
hour = millisecond / (60 * 60 * 1000);
return hour;
}
/**
* 比较两个时间相差分钟
*/
public static double calculatetimeGapMinute(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
double minute = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
minute = millisecond / (60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return minute;
}
/**
* 比较两个时间相差分钟
*/
public static double calculatetimeGapMinute(Date date1, Date date2) {
double minute = 0;
double millisecond = date2.getTime() - date1.getTime();
minute = millisecond / (60 * 1000);
return minute;
}
/**
* 比较两个时间相差秒
*/
public static double calculatetimeGapSecond(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
double second = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
second = millisecond / (1000);
} catch (ParseException e) {
e.printStackTrace();
}
return second;
}
/**
* 比较两个时间相差秒
*/
public static double calculatetimeGapSecond(Date date1, Date date2) {
double second = 0;
double millisecond = date2.getTime() - date1.getTime();
second = millisecond / (1000);
return second;
}
/**
* 时间工具
*
* @param ctime 入参
* @return 返回
*/
public static String showTime(Date ctime) {
String r = "";
if (ctime == null) {
return r;
}
String format = "yyyy-MM-dd HH:mm:ss";
long nowtimelong = System.currentTimeMillis();
long ctimelong = ctime.getTime();
long result = Math.abs(nowtimelong - ctimelong);
if (result < 60000) {// 一分钟内
long seconds = result / 1000;
if (seconds == 0) {
r = "刚刚";
} else {
r = seconds + "秒前";
}
} else if (result >= 60000 && result < 3600000) {// 一小时内
long seconds = result / 60000;
r = seconds + "分钟前";
} else if (result >= 3600000 && result < 86400000) {// 一天内
long seconds = result / 3600000;
r = seconds + "小时前";
} else if (result >= 86400000 && result < 1702967296) {// 三十天内
long seconds = result / 86400000;
r = seconds + "天前";
} else {// 日期格式
SimpleDateFormat df = new SimpleDateFormat(format);
r = df.format(ctime);
}
return r;
}
/**
* 根据对应语言-显示对应格式
* languageCode:国际语言编码:en zh
* date:需处理的日期
*/
public static String formatDateByObject(String languageCode, Object date) {
if (StringUtils.isEmpty(languageCode) || date == null || StringUtils.isEmpty(date.toString())) {
return "";
} else {
return DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale(languageCode)).format(date);
}
}
/**
* 根据对应语言-显示对应格式
* languageCode:国际语言编码:en zh
* date:需处理的日期
* 注:通过sql语句查询出来的date不能转换成Date类型来调用此方法 应直接调用用formatDateByObject方法
*/
public static String formatDateByDate(String languageCode, Date date) {
if (StringUtils.isEmpty(languageCode) || date == null || StringUtils.isEmpty(date.toString())) {
return "";
} else {
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale(languageCode));
return df.format(date);
}
}
/**
* 获取当前时间 默认返回 yyyy-MM-dd HH:mm:ss
*
* @return 当前时间字符串
*/
public static String nowTime(String pattern) {
//return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern).format(new Date());
return localDateTimeToString(LocalDateTime.now(), StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern);
}
/**
* 获取当前日期 默认返回 yyyy-MM-dd
*
* @return 当前日期字符串
*/
public String today(String pattern) {
//return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern).format(new Date());
return localDateToString(LocalDate.now(), StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern);
}
/**
* 日期格式化 Date 转 String
* 默认返回 yyyy-MM-dd HH:mm:ss
*
* @param date 日期 必填
* @param pattern 转换格式
* @return 返回格式后日期
*/
public static String dateToString(Date date, String pattern) {
if (date == null) {
return null;
} else {
return new SimpleDateFormat(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern).format(date);
}
}
/**
* String 转 LocalDate
*
* @param date 待转换的字符串 必填
* @param pattern 转换格式 默认为yyyy-MM-dd
* @return
*/
public static LocalDate stringToLocalDate(String date, String pattern) {
if (StringUtils.isEmpty(date)) {
return null;
} else {
return LocalDate.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern));
}
}
/**
* String 转 LocalDateTime
*
* @param date 待转换的字符串 必填
* @param pattern 转换格式 默认为yyyy-MM-dd HH:mm:ss
* @return
*/
public static LocalDateTime stringToLocalDateTime(String date, String pattern) {
if (StringUtils.isEmpty(date)) {
return null;
} else {
return LocalDateTime.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern));
}
}
/**
* String 转 LocalTime
*
* @param date 待转换的字符串 必填
* @param pattern 转换格式 默认为HH:mm:ss
* @return
*/
public static LocalTime stringToLocalTime(String date, String pattern) {
if (StringUtils.isEmpty(date)) {
return null;
} else {
return LocalTime.parse(date, java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "HH:mm:ss" : pattern));
}
}
/**
* LocalDate 转 String
*
* @param localDate
* @param pattern
* @return
*/
public static String localDateToString(LocalDate localDate, String pattern) {
return localDate.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd" : pattern));
}
/**
* LocalDateTime 转 String
*
* @param localDateTime
* @param pattern
* @return
*/
public static String localDateTimeToString(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "yyyy-MM-dd HH:mm:ss" : pattern));
}
/**
* LocalTime 转 String
*
* @param localTime
* @param pattern
* @return
*/
public static String localTimeToString(LocalTime localTime, String pattern) {
return localTime.format(java.time.format.DateTimeFormatter.ofPattern(StringUtils.isEmpty(pattern) ? "HH:mm:ss" : pattern));
}
/**
* LocalDate 转 Date
*
* @param localDate
* @return
*/
public static Date localDateToDate(LocalDate localDate) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
return Date.from(zdt.toInstant());
}
/**
* LocalDateTime 转 Date
*
* @param localDateTime
* @return
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
return Date.from(zdt.toInstant());
}
/**
* LocalDateTime 转 LocalDate
*
* @param localDateTime
* @return
*/
public static LocalDate localDateTimeToLocalDate(LocalDateTime localDateTime) {
return localDateTime.toLocalDate();
}
/**
* LocalDateTime 转 LocalTime
*
* @param localDateTime
* @return
*/
public static LocalTime localDateTimeToLocalTime(LocalDateTime localDateTime) {
return localDateTime.toLocalTime();
}
/**
* Date 转 LocalDate
* atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
*
* @param date
* @return
*/
public static LocalDate dateToLocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDate();
}
/**
* 将 Date 转 LocalDateTime
* atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
*
* @param date
* @return
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDateTime();
}
/**
* 将 Date 转 LocalTime
* atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
*
* @param date
* @return
*/
public static LocalTime dateToLocalTime(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalTime();
}
/**
* 计算两个LocalDateTime yyyy-MM-dd HH:mm:ss 之间的 时间间隔
*
* @param localDateTime1
* @param localDateTime2
* @return Map<String, Object>
* millis:毫秒差
* seconds:秒差
* minutes:分钟差
* hours:小时差
* days:天数差
* weeks:周差
* months:月份差
* quarters:季度差
* years:年份差
*/
public static Map<String, Object> minusToLocalDateTime(LocalDateTime localDateTime1, LocalDateTime localDateTime2) {
Duration duration = Duration.between(localDateTime1, localDateTime2);
Map<String, Object> map = new HashMap<>(16);
//毫秒差
map.put("millis", duration.toMillis());
//秒差
map.put("seconds", duration.toMillis() / 1000);
//分钟差
map.put("minutes", duration.toMinutes());
//小时差
map.put("hours", duration.toHours());
//天数差
map.put("days", duration.toDays());
//周差
map.put("weeks", duration.toDays() / 7);
Map<String, Object> map1 = minusToLocalDate(localDateTime1.toLocalDate(), localDateTime2.toLocalDate());
//季度差
map.put("quarters", map1.get("quarters"));
//月份差
map.put("months", map1.get("months"));
//年份差
map.put("years", map1.get("years"));
return map;
}
/**
* 计算两个LocalTime HH:mm:ss 之间的 时间间隔
*
* @param localTime1
* @param localTime2
* @return Map<String, Object>
* millis:毫秒差
* seconds:秒差
* minutes:分钟差
* hours:小时差
*/
public static Map<String, Object> minusToLocalTime(LocalTime localTime1, LocalTime localTime2) {
Duration duration = Duration.between(localTime1, localTime2);
Map<String, Object> map = new HashMap<>(16);
//毫秒差
map.put("millis", duration.toMillis());
//秒差
map.put("seconds", duration.toMillis() / 1000);
//分钟差
map.put("minutes", duration.toMinutes());
//小时差
map.put("hours", duration.toHours());
return map;
}
/**
* 计算两个LocalDate yyyy-MM-dd 之间的 时间间隔
*
* @param localDate1
* @param localDate2
* @return Map<String, Object>
* days:天数差
* weeks:周差
* months:月份差
* quarters:季度差
* years:年份差
*/
public static Map<String, Object> minusToLocalDate(LocalDate localDate1, LocalDate localDate2) {
Period period = localDate1.until(localDate2);
Map<String, Object> map = new HashMap<>(16);
//天数差
map.put("days", period.getDays());
//周差
map.put("weeks", period.getDays() / 7);
//月份差
map.put("months", period.getMonths());
// 季度差
map.put("quarters", period.getMonths() / 3);
//年份差
map.put("years", period.getYears());
return map;
}
/**
* 根据时间 和时间格式 校验是否正确
* 示例:
* String date = "2020-01-25 12:36:45";
* 传入date的长度、data、"yyyy-MM-dd HH:mm:ss" = true 《或者》 传入date的长度、data、"yyyy-MM-dd" = false
* @param length 校验的长度
* @param sDate 校验的日期
* @param format 校验的格式
* @return
*/
public static boolean isLegalDate(int length, String sDate,String format) {
int legalLen = length;
if ((sDate == null) || (sDate.length() != legalLen)) {
return false;
}
DateFormat formatter = new SimpleDateFormat(format);
try {
Date date = formatter.parse(sDate);
return sDate.equals(formatter.format(date));
} catch (Exception e) {
return false;
}
}
}
package com.pashanhoo.common.minio;
import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@Component
public class FileServerOptUtil {
private Logger log = LoggerFactory.getLogger(FileServerOptUtil.class);
@Autowired
MinioClient minioClient;
/**
* 获取桶中某个对象的输入流
* @param bucketName
* @param path
* @return
*/
public InputStream getObjectInputStream(String bucketName, String path){
log.info("从桶:" + bucketName + ",获取:" + path + "对象流!");
InputStream stream = null;
try {
stream = minioClient.getObject(
GetObjectArgs.builder().bucket(bucketName).object(path).build());
} catch (Exception e) {
log.error("从桶:" + bucketName + ",获取:" + path + "对象流错误!");
e.printStackTrace();
}
return stream;
}
/**
*
* @param bucketName
* @param dirPath 如:path/to/
* @return
*/
public boolean mkdir(String bucketName,String dirPath){
log.info("在桶:" + bucketName + ",中创建:" + dirPath);
boolean result = false;
try {
minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(dirPath).stream(
new ByteArrayInputStream(new byte[] {}), 0, -1)
.build());
result = true;
} catch (Exception e) {
log.error("在桶:" + bucketName + ",中创建:" + dirPath + "错误!");
e.printStackTrace();
}
return result;
}
/**
* 往对象存储服务目标桶的目标位置上传文件
* @param bucketName 桶
* @param toPath 目标位置如:test/2.txt
* @param fromPath 本地文件位置
* @return
*/
public boolean uploadObject(String bucketName,String toPath,String fromPath ){
log.info("从本地:" + fromPath + "往桶:" + bucketName + ",中上传文件:" + toPath);
boolean result = false;
try {
minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName)
.object(toPath)
.filename(fromPath)
.build());
result = true;
} catch (Exception e) {
log.error("从本地:" + fromPath + "往桶:" + bucketName + ",中上传文件:" + toPath + "错误!");
e.printStackTrace();
}
return result;
}
/**
* 从桶中下载文件到本地文件
* @param bucketName
* @param fromPath
* @param toPath
* @return
*/
public boolean downloadFile(String bucketName,String fromPath,String toPath){
log.info("从桶:" + bucketName + "中将" + fromPath + "文件下载到:" + toPath);
boolean result = false;
try {
minioClient.downloadObject(
DownloadObjectArgs.builder()
.bucket(bucketName)
.object(fromPath)
.filename(toPath)
.build());
result = true;
} catch (Exception e) {
log.error("从桶:" + bucketName + "中将" + fromPath + "文件下载到:" + toPath + "错误!");
e.printStackTrace();
}
return result;
}
public static String extractFilename(MultipartFile file){
if (file.isEmpty()) {
throw new RuntimeException("文件不存在!");
}
return DateUtils.dateToStr(new Date()) + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename() ;
}
}
\ No newline at end of file
package com.pashanhoo.common.minio;
import io.minio.MinioClient;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
private Logger log = LoggerFactory.getLogger(MinioConfig.class);
// minio地址
private String minioUrl;
//minio账号
private String accessKey;
//minio密码
private String secretKey;
//存储桶名称 */
public String bucketName;
// "如果是true,则用的是https而不是http,默认值是true"
public static Boolean secure = false;
@Bean
public MinioClient getMinioClient(){
log.info("初始化MinioClient客户端:minioUrl:" + minioUrl + ",accessKey:" + accessKey + ",secretKey:" + secretKey);
MinioClient minioClient = MinioClient.builder()
.endpoint(minioUrl)
.credentials(accessKey,secretKey)
.build();
return minioClient;
}
}
package com.pashanhoo.common.minio;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@Component
public class MinioUtil {
@Autowired
private MinioClient minioClient;
/**
* 查看存储bucket是否存在
*
* @param bucketName 存储bucket
* @return boolean
*/
public Boolean bucketExists(String bucketName) {
Boolean found;
try {
found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return found;
}
/**
* 创建存储bucket
*
* @param bucketName 存储bucket名称
* @return Boolean
*/
public Boolean makeBucket(String bucketName) {
try {
minioClient.makeBucket(MakeBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 删除存储bucket
*
* @param bucketName 存储bucket名称
* @return Boolean
*/
public Boolean removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder()
.bucket(bucketName)
.build());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 文件上传
*
* @param file 文件
* @param bucketName 存储bucket
* @return Boolean
*/
public Boolean upload(MultipartFile file, String fileName, String bucketName) {
try {
PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
.stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
//文件名称相同会覆盖
minioClient.putObject(objectArgs);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 文件下载
*
* @param bucketName 存储bucket名称
* @param fileName 文件名称
* @param res response
* @return Boolean
*/
public void download(String bucketName, String fileName, HttpServletResponse res) {
GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
.object(fileName).build();
try (GetObjectResponse response = minioClient.getObject(objectArgs)) {
byte[] buf = new byte[1024];
int len;
try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()) {
while ((len = response.read(buf)) != -1) {
os.write(buf, 0, len);
}
os.flush();
byte[] bytes = os.toByteArray();
res.setCharacterEncoding("utf-8");
//设置强制下载不打开
res.setContentType("application/force-download");
res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
try (ServletOutputStream stream = res.getOutputStream()) {
stream.write(bytes);
stream.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查看文件对象
*
* @param bucketName 存储bucket名称
* @return 存储bucket内文件对象信息
*/
public List<ObjectItem> listObjects(String bucketName) {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).build());
List<ObjectItem> objectItems = new ArrayList<>();
try {
for (Result<Item> result : results) {
Item item = result.get();
ObjectItem objectItem = new ObjectItem();
objectItem.setObjectName(item.objectName());
objectItem.setSize(item.size());
objectItems.add(objectItem);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return objectItems;
}
/**
* 批量删除文件对象
*
* @param bucketName 存储bucket名称
* @param objects 对象名称集合
*/
public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
return results;
}
}
package com.pashanhoo.common.minio;
import io.swagger.annotations.ApiModel;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@ApiModel("用户实体类")
public class ObjectItem {
long size;
String objectName;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
}
package com.pashanhoo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/8/18
*/
@Configuration
@Slf4j
public class TestTemplateBeanConfig {
@Bean
RestTemplate restTemplate(){
log.info("完成初始化RestTemplate得bean");
return new RestTemplate();
}
}
package com.pashanhoo.qys.controller;
import com.pashanhoo.common.Result;
import com.pashanhoo.qys.service.SysFileService;
import io.minio.GetObjectArgs;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.messages.Item;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@Api(tags = "Minio文件上传")
@RestController
@RequestMapping("/system/file")
public class SysFileController {
@Autowired
private SysFileService sysFileService;
@Autowired
private MinioClient minioClient;
/**
* 图片上传minio
*
* @param file 图片文件
* @return 返回
*/
@ApiOperation("点选文件-文件上传")
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Result uploadFileMinio(MultipartFile file) {
String url = sysFileService.uploadFileMinio(file);
if (!StringUtils.isEmpty(url)) {
return Result.ok(url);
}
return Result.error(-1,"上传失败");
}
@PostMapping(value = "/upload-files" )
@ApiOperation(value = "文件上传(支持批量)", notes = "文件上传(支持批量)")
public Result uploadFiles(@RequestPart MultipartFile[] files ) throws IOException {
String url = sysFileService.uploadFileMinio(files);
if (!StringUtils.isEmpty(url)) {
return Result.ok(url);
}
return Result.error(-1,"上传失败");
}
// 暂未实现
@ApiOperation("文件下载")
@RequestMapping(value = "/download", method = RequestMethod.POST)
public String download(HttpServletResponse response) {
try {
Iterable<io.minio.Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket("eci-bucket").build()//获取bucket里所有文件信息
);
String fileName = null;
for (io.minio.Result<Item> result : results) {
Item item = result.get();
fileName = item.objectName();
System.out.println(item.lastModified() + "\t" + item.size() + "\t" + item.objectName());
}
InputStream object = minioClient.getObject(GetObjectArgs.builder().bucket("eci-bucket").object(fileName).build());
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
IOUtils.copy(object, bos);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
bos.flush();
return "success";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
}
\ No newline at end of file
package com.pashanhoo.qys.service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
public interface SysFileService {
public String uploadFileMinio(MultipartFile file);
public String uploadFileMinio(MultipartFile[] file);
}
package com.pashanhoo.qys.service.impl;
import com.pashanhoo.common.minio.FileServerOptUtil;
import com.pashanhoo.common.minio.MinioConfig;
import com.pashanhoo.common.minio.MinioUtil;
import com.pashanhoo.qys.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author CAIYONGSONG
* @commpany www.pashanhoo.com
* @date 2022/7/20
*/
@Service
@Slf4j
public class SysFileServiceImpl implements SysFileService {
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioUtil minioUtil;
@Override
public String uploadFileMinio(MultipartFile[] files){
Long st = System.currentTimeMillis();
log.info("开始上传批量文件" + files.length);
// 判断存储桶是否存在
if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
minioUtil.makeBucket(minioConfig.getBucketName());
}
StringBuilder sbf = new StringBuilder();
for (MultipartFile file : files) {
if (file.isEmpty()) {
throw new RuntimeException("文件不存在!");
}
log.info("循环开始上传单个文件,文件大小:" + file.getSize());
// 生成文件名 按照要求-带文件夹路径的文件的全路径
String fineName = FileServerOptUtil.extractFilename(file);
try {
// 上传文件
minioUtil.upload(file, fineName, minioConfig.getBucketName());
} catch (Exception e) {
System.out.println("上传minio服务器期出错了 " + e.getMessage());
e.printStackTrace();
return null;
}
sbf.append(minioConfig.getMinioUrl()).append("/").append( minioConfig.getBucketName())
.append("/").append(fineName).append(",");
}
//String url = minioConfig.getMinioUrl() + "/" + minioConfig.getBucketName() + "/" + fineName;
String resUrl = sbf.toString().substring(0,(sbf.length()-1));
log.info("上传文件结束,总耗时:"+(System.currentTimeMillis() - st) +"s, 文件路径:" + resUrl );
return resUrl;
}
@Override
public String uploadFileMinio(MultipartFile file) {
Long st = System.currentTimeMillis();
if (file.isEmpty()) {
throw new RuntimeException("文件不存在!");
}
log.info("开始上传单个文件,文件大小:" + (file.getSize()/1024) + "KB");
// 判断存储桶是否存在
if (!minioUtil.bucketExists(minioConfig.getBucketName())) {
minioUtil.makeBucket(minioConfig.getBucketName());
}
// 生成文件名 按照要求-带文件夹路径的文件的全路径
String fineName = FileServerOptUtil.extractFilename(file);
try {
// 上传文件
minioUtil.upload(file, fineName, minioConfig.getBucketName());
} catch (Exception e) {
System.out.println("上传minio服务器期出错了 " + e.getMessage());
e.printStackTrace();
return null;
}
String url = minioConfig.getMinioUrl() + "/" + minioConfig.getBucketName() + "/" + fineName;
log.info("上传文件结束,总耗时:"+(System.currentTimeMillis() - st) +"ms, 文件路径:" + url );
return url;
}
}
\ No newline at end of file
......@@ -7,8 +7,8 @@ server:
spring:
servlet:
multipart:
maxFileSize: 10MB
maxRequestSize: 10MB
maxFileSize: 100MB
maxRequestSize: 500MB
application:
name: hzbdcsyn
jackson:
......@@ -71,5 +71,16 @@ management:
logging:
config: "classpath:logback-spring.xml"
# Minio配置
minio:
# minio配置的地址,端口9000
minioUrl: http://172.16.56.30:90
# 账号
accessKey: minioadmin
# 密码
secretKey: minioadmin
# MinIO桶名字
bucketName: ecibucket
swagger2:
enable: false
......
......@@ -7,8 +7,8 @@ server:
spring:
servlet:
multipart:
maxFileSize: 10MB
maxRequestSize: 10MB
maxFileSize: 100MB
maxRequestSize: 500MB
application:
name: hzbdcsyn
jackson:
......@@ -71,5 +71,16 @@ management:
logging:
config: "classpath:logback-spring.xml"
# Minio配置
minio:
# minio配置的地址,端口9000
minioUrl: http://172.16.56.30:90
# 账号
accessKey: minioadmin
# 密码
secretKey: minioadmin
# MinIO桶名字
bucketName: ecibucket
swagger2:
enable: true
......
spring:
profiles:
active: dev
active: test
......