提交 87f8efc5 编写于 作者: Skyeye云's avatar Skyeye云

基础jar包

上级 ffb239d0
......@@ -57,6 +57,7 @@
<module>skyeye-api</module>
<module>skyeye-ifs</module>
<module>skyeye-boss</module>
<module>skyeye-base</module>
</modules>
<properties>
......
<?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"
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>
<parent>
<artifactId>skyeye-promote</artifactId>
<groupId>com.skyeye</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>skyeye-base</artifactId>
<name>skyeye-base</name>
<url>http://www.example.com</url>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率 https://apidoc.gitee.com/loolly/hutool/ -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<version>5.5.4</version>
</dependency>
<dependency>
<groupId>com.gexin.platform</groupId>
<artifactId>gexin-rp-sdk-http</artifactId>
<version>4.1.0.5</version>
<exclusions>
<exclusion>
<artifactId>protobuf-java</artifactId>
<groupId>com.google.protobuf</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<repositories>
<repository>
<id>getui-nexus</id>
<url>http://mvn.gt.igexin.com/nexus/content/repositories/releases/</url>
</repository>
</repositories>
</project>
\ No newline at end of file
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.constans;
import cn.hutool.core.util.ArrayUtil;
import java.util.*;
/**
*
* @ClassName: Constants
* @Description: 系统公共常量类
* @author: skyeye云系列--卫志强
* @date: 2021/6/6 23:22
*
* @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved.
* 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的
*/
public class Constants {
/**
* 过滤器过滤内容请求项
*/
public static final String[] FILTER_FILE_CATALOG_OPTION = { "/html", "/css", "/js", "/assets", "/tpl", "/images",
"/template", "/static", ".json", ".css", ".js", ".gif", ".jpg", ".eot", ".svg", ".ttf", ".woff", ".woff2",
".mp4", ".rmvb", ".avi", "3gp", ".html", ".less", ".otf", ".scss", ".ico", "/upload", "/actuator",
"/service", "/talkwebsocket", "/phonetalkwebsocket" };
/**
* 百分号
*/
public static final String PERCENT_SIGN = "%";
/**
* 中文
*/
public static String LANGUAGE_ZH = "zh";
/**
* 英文
*/
public static String LANGUAGE_CN = "cn";
/**
* IP过滤
*/
public static final String[] FILTER_FILE_IP_OPTION = { "0:0:0:0:0:0:0:1", "127.0.0.1" };
/**
* 过滤器过滤请求类型项
*/
public static final String[] FILTER_FILE_REQUEST_OPTION = { "/post", "/websocket", "/service" };
/**
* 登录页面
*/
public static final String LOGIN_PAGE = "/tpl/index/login.html";
/**
* 系统请求参数集合
*/
public static Map<String, Map<String, Object>> REQUEST_MAPPING = null;
/**
* json数据请求发送的数据格式
*/
public static final String CONENT_TYPE_JSON_REQ = "application/json";
/**
* 菜单类型
*/
public static final String SYS_MENU_TYPE_IS_IFRAME = "win";
public static final String SYS_MENU_TYPE_IS_HTML = "html";
/**
* 菜单链接打开类型,父菜单默认为1.1:打开iframe,2:打开html。
*/
public static final String SYS_MENU_OPEN_TYPE_IS_IFRAME = "1";
public static final String SYS_MENU_OPEN_TYPE_IS_HTML = "2";
/**
* 保存模板说明的redis的key
*/
public static final String REDIS_CODEMODEL_EXPLAIN_EXEXPLAIN = "exexplaintocodemodel";
public static String getSysExplainExexplainRedisKey(Integer type) {
return REDIS_CODEMODEL_EXPLAIN_EXEXPLAIN + "_" + type;
}
/**
* 可以设置长些,防止读到运行此次系统检查时的cpu占用率,就不准了
*/
public static final int PERCENT = 100;
public static final int FAULTLENGTH = 10;
// win系统桌面图片列表的redis的key
public static final String SYS_WIN_BG_PIC_REDIS_KEY = "sys_win_bg_pic_redis_key";
public static String getSysWinBgPicRedisKey() {
return SYS_WIN_BG_PIC_REDIS_KEY;
}
// win系统锁屏桌面图片列表的redis的key
public static final String SYS_WIN_LOCK_BG_PIC_REDIS_KEY = "sys_win_lock_bg_pic_redis_key";
public static String getSysWinLockBgPicRedisKey() {
return SYS_WIN_LOCK_BG_PIC_REDIS_KEY;
}
// win系统主题颜色列表的redis的key
public static final String SYS_WIN_THEME_COLOR_REDIS_KEY = "sys_win_theme_color_redis_key";
public static String getSysWinThemeColorRedisKey() {
return SYS_WIN_THEME_COLOR_REDIS_KEY;
}
// 开发文档获取一级分类列表的redis的key
public static final String SYS_DEVE_LOP_DOC_FIRST_TYPE = "sys_deve_lop_doc_first_type";
public static String getSysDeveLopDocFirstType() {
return SYS_DEVE_LOP_DOC_FIRST_TYPE;
}
// 开发文档获取二级分类列表的redis的key
public static final String SYS_DEVE_LOP_DOC_SECOND_TYPE = "sys_deve_lop_doc_second_type_";
public static String getSysDeveLopDocSecondType(String parentId) {
return SYS_DEVE_LOP_DOC_SECOND_TYPE + parentId;
}
// 开发文档获取文档标题列表的redis的key
public static final String SYS_DEVE_LOP_DOC_TITLE_LIST = "sys_deve_lop_doc_title_list_";
public static String getSysDeveLopDocTitleList(String parentId) {
return SYS_DEVE_LOP_DOC_TITLE_LIST + parentId;
}
// 开发文档获取文档内容的redis的key
public static final String SYS_DEVE_LOP_DOC_CONTENT = "sys_deve_lop_doc_content_";
public static String getSysDeveLopDocContent(String id) {
return SYS_DEVE_LOP_DOC_CONTENT + id;
}
// 聊天获取当前登陆用户信息在redis中的key
public static final String SYS_TALK_USER_THIS_MATN_MATION = "sys_talk_user_this_matn_mation_";
public static String getSysTalkUserThisMainMationById(String id) {
return SYS_TALK_USER_THIS_MATN_MATION + id;
}
// 聊天获取当前登陆用户拥有的群组列表在redis中的key
public static final String SYS_TALK_USER_HAS_GROUP_LIST_MATION = "sys_talk_user_has_group_list_mation_";
public static String getSysTalkUserHasGroupListMationById(String id) {
return SYS_TALK_USER_HAS_GROUP_LIST_MATION + id;
}
// 聊天获取分组下的用户列表信息在redis中的key
public static final String SYS_TALK_GROUP_USER_LIST_MATION = "sys_talk_group_user_list_mation_";
public static String getSysTalkGroupUserListMationById(String id) {
return SYS_TALK_GROUP_USER_LIST_MATION + id;
}
// 获取已经上线的图片类型列表的redis的key
public static final String SYS_EVE_PIC_TYPE_UP_STATE_LIST = "sys_eve_pic_type_up_state_list";
public static String sysEvePicTypeUpStateList() {
return SYS_EVE_PIC_TYPE_UP_STATE_LIST;
}
// 获取已经上线的申诉原因的redis的key
public static final String CHECK_WORK_REASON_UP_STATE_LIST = "check_work_reason_up_state_list";
public static String checkWorkReasonUpStateList() {
return CHECK_WORK_REASON_UP_STATE_LIST;
}
// 获取已经上线的轻应用类型的redis的key
public static final String CHECK_APP_LIGHTAPPTYPE_UP_LIST = "check_app_lightapptype_up_list";
public static String checkAppLightAppTypeUpList() {
return CHECK_APP_LIGHTAPPTYPE_UP_LIST;
}
// 获取已经上线的轻应用的redis的key
public static final String CHECK_APP_LIGHTAPP_UP_LIST_BYID = "check_app_lightapp_up_list_byid_";
public static String checkAppLightAppUpListById(String typeId) {
return CHECK_APP_LIGHTAPP_UP_LIST_BYID + typeId;
}
// 获取我的附件0级列表
public static final List<Map<String, Object>> getSysEnclosureZeroList() {
List<Map<String, Object>> beans = new ArrayList<>();
Map<String, Object> favorites = new HashMap<>();
favorites.put("id", "1");
favorites.put("name", "我的附件");
favorites.put("pId", "0");
favorites.put("isParent", 1);// 是否是文件夹 0否1是
favorites.put("icon", "../../assets/images/my-folder-icon.png");// 图标
beans.add(favorites);
return beans;
}
// 附件分块上传时的分块集合存储key
public static final String SYS_ENCLOSURE_FILE_MODULE_MD5 = "sys_enclosure_file_module_md5_";
public static String getSysEnclosureFileModuleByMd5(String md5) {
return SYS_ENCLOSURE_FILE_MODULE_MD5 + md5;
}
// 系统读取请求配置文件的key
public static final String SYS_EVE_MAIN_REQMAPPING_KEY = "sys_eve_main_reqmapping_key_skyeye";
/**
* 星期几
*/
public static enum WeekDay {
MON("星期一", 1),
TUE("星期二", 2),
WED("星期三", 3),
THU("星期四", 4),
FRI("星期五", 5),
SAT("星期六", 6),
SUN("星期日", 7);
private String name;
private int day;
WeekDay(String name, int day) {
this.name = name;
this.day = day;
}
public static String getWeekName(Date date) {
Calendar cal = Calendar.getInstance();
// 一周第一天是否为星期天
boolean isFirstSunday = (cal.getFirstDayOfWeek() == Calendar.SUNDAY);
cal.setTime(date);
int weekDay = cal.get(Calendar.DAY_OF_WEEK);// 获取星期
// 若一周第一天为星期天,则-1
if (isFirstSunday) {
weekDay = weekDay - 1;
if (weekDay == 0) {
weekDay = 7;
}
}
for (WeekDay q : WeekDay.values()) {
if (q.getDay() == weekDay) {
return q.getName();
}
}
return null;
}
public String getName() {
return name;
}
public int getDay() {
return day;
}
}
/**
* 文件上传路径
*/
public static enum FileUploadPath {
SMPROPIC(new int[]{1}, "/smpropic", "/", "小程序上传"),
WINBGPIC(new int[]{2, 4}, "/winbgpic", "/winbgpic/", "系统桌面背景自定义图片上传,系统桌面背景自定义图片上传用户自定义"),
WINLOCKBGPIC(new int[]{3, 5}, "/winlockbgpic", "/winlockbgpic/", "系统桌面锁屏背景自定义图片上传,系统桌面锁屏背景自定义图片上传用户自定义"),
USERPHOTO(new int[]{6}, "/userphoto", "/userphoto/", "用户头像"),
TALKGROUP(new int[]{7}, "/talkgroup", "/talkgroup/", "聊天群组头像"),
SYSWIN(new int[]{8}, "/syswin", "/syswin/", "系统图片"),
TALKPIC(new int[]{9}, "/talkpic", "/talkpic/", "聊天图片"),
TALKFILE(new int[]{10}, "/talkfile", "/talkfile/", "聊天附件"),
EDIT(new int[]{11}, "/edit", "/edit/", "富文本内容图片"),
MENULOGO(new int[]{12}, "/menulogo", "/menulogo/", "菜单logo图片"),
LAYEDIT(new int[]{13}, "/layedit", "/layedit/", "富文本编辑图片"),
ORDER(new int[]{14}, "/order", "/order/", "工单图片"),
STUDENTPIC(new int[]{15}, "/studentPic", "/studentPic/", "学生照图片"),
SCHOOLBANK(new int[]{16}, "/schoolBank", "/schoolBank/", "考试题库文件"),
ACT_MODEL(new int[]{17}, "/actmodel", "/actmodel/", "流程配置图片"),
REPORT_BG_IMAGE(new int[]{18}, "/reportBgImage", "/reportBgImage/", "报表基础设置背景图"),
REPORT_WORD_MODEL_IMAGE(new int[]{19}, "/reportWordModel", "/reportWordModel/", "报表文字模型logo"),
SYS_MODEL(new int[]{20}, "/sysmodel", "/sysmodel/", "编辑器素材logo图片"),;
private int[] type;
// 保存地址
private String savePath;
// 访问地址
private String visitPath;
private String desc;
FileUploadPath(int[] type, String savePath, String visitPath, String desc) {
this.type = type;
this.savePath = savePath;
this.visitPath = visitPath;
this.desc = desc;
}
public int[] getType() {
return type;
}
public String getSavePath() {
return savePath;
}
public String getVisitPath() {
return visitPath;
}
public String getDesc() {
return desc;
}
public static String getSavePath(int type) {
for (FileUploadPath q : FileUploadPath.values()) {
if (ArrayUtil.contains(q.getType(), type)) {
return "/upload" + q.getSavePath();
}
}
return "/upload";
}
public static String getVisitPath(int type) {
for (FileUploadPath q : FileUploadPath.values()) {
if (ArrayUtil.contains(q.getType(), type)) {
return "/images/upload" + q.getVisitPath();
}
}
return "/images/upload/";
}
}
// 获取群组成员列表
public static final String SYS_EVE_TALK_GROUP_USER_LIST = "sys_eve_talk_group_user_list_";
public static String checkSysEveTalkGroupUserListByGroupId(String groupId) {
return SYS_EVE_TALK_GROUP_USER_LIST + groupId;
}
// 获取上线的申请类型下的上线的类型实体
public static final String ACT_MODLE_UP_STATE_LIST = "act_modle_up_state_list";
// 我的个人通讯录类型列表
public static final String PERSON_MAIL_TYPE_LIST = "person_mail_type_list_";
public static String getPersonMailTypeListByUserId(String userId) {
return PERSON_MAIL_TYPE_LIST + userId;
}
// 获取已经上线的论坛举报类型的redis的key
public static final String FORUM_REPORT_TYPE_UP_LIST = "forum_report_type_up_list";
public static String forumReportTypeUpList() {
return FORUM_REPORT_TYPE_UP_LIST;
}
// 获取redis中的动态表单页
public static final String DS_FORM_CONTENT_LIST_BY_PAGE_ID = "ds_form_content_list_by_page_id_";
public static String dsFormContentListByPageId(String pageId) {
return DS_FORM_CONTENT_LIST_BY_PAGE_ID + pageId;
}
// 工作流流程在redis中的存储
public static final String PROCESS_REDIS_CACHE_KEY = "process_redis_cache_key_";
public static String getActProcessInstanceRedisCacheKey(String processInstanceId) {
return PROCESS_REDIS_CACHE_KEY + processInstanceId;
}
/**
*
* @param orderNum 获取工单派工内容字符串
* @param userName 接收人
* @return
*/
public static String getNoticeServiceUserContent(String orderNum, String userName) {
return "尊敬的" + userName + ",您好:<br/>" + "您有一份待接单工单,工单号为:" + orderNum + ",请及时接单。";
}
// 协助人
public static String getNoticeCooperationUserContent(String orderNum, String userName) {
return "尊敬的" + userName + ",您好:<br/>" + "您有一份协助工单,工单号为:" + orderNum + ",请配合工单接收人完成该售后服务。";
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.constans;
/**
* @ClassName: RedisConstants
* @Description: redis常用工具类
* @author: skyeye云系列--卫志强
* @date: 2021/12/3 20:54
* @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved.
* 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的
*/
public class RedisConstants {
/**
* 默认key失效时间为十天
*/
public static final int TEN_DAY_SECONDS = 10 * 24 * 60 * 60;
/**
* 默认key失效时间30天
*/
public static final int THIRTY_DAY_SECONDS = 30 * 24 * 60 * 60;
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* request 对象的相关操作
* @author 卫志强
* @version 1.0
* @created 2017年07月02日 上午8:25:43
*/
public class GetRequestJsonUtils {
/***
* 获取 request 中 json 字符串的内容
*
* @param request
* @return : <code>byte[]</code>
* @throws IOException
*/
public static String getRequestJsonString(HttpServletRequest request) throws IOException {
String submitMehtod = request.getMethod();
// GET
if (submitMehtod.equals("GET")) {
return new String(request.getQueryString().getBytes("iso-8859-1"), "utf-8").replaceAll("%22", "\"");
// POST
} else {
return getRequestPostStr(request);
}
}
/**
* 描述:获取 post 请求的 byte[] 数组
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static byte[] getRequestPostBytes(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
if(contentLength<0){
return null;
}
byte[] buffer = new byte[contentLength];
for (int i = 0; i < contentLength;) {
int readlen = request.getInputStream().read(buffer, i,
contentLength - i);
if (readlen == -1) {
break;
}
i += readlen;
}
return buffer;
}
/**
* 描述:获取 post 请求内容
* <pre>
* 举例:
* </pre>
* @param request
* @return
* @throws IOException
*/
public static String getRequestPostStr(HttpServletRequest request) throws IOException {
byte[] buffer = getRequestPostBytes(request);
String charEncoding = request.getCharacterEncoding();
if (charEncoding == null) {
charEncoding = "UTF-8";
}
return new String(buffer, charEncoding);
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import com.skyeye.common.util.ToolUtil;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class GetUserToken {
private static final String PHONE_TOKEN_SUFFIX = "-APP";
private static final String USERTOKEN_KEY = "userToken";
/**
* 从cookies获取内容
* @param request
* @param name
* @return
*/
public static String getCookiesByName(HttpServletRequest request, String name){
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals(name)){
return cookie.getValue();
}
}
}
return "";
}
/**
* 获取userToken
* @param request
* @return userToken
* @throws Exception
*/
public static String getUserToken(HttpServletRequest request) throws Exception{
// 1.从请求信息中获取
String userToken = request.getParameter(USERTOKEN_KEY);
// 2.从cookies中获取
if(StringUtils.isBlank(userToken)){
userToken = getCookiesByName(request, USERTOKEN_KEY);
}
// 3.从header中获取
if(StringUtils.isBlank(userToken)){
userToken = request.getHeader(USERTOKEN_KEY);
}
if(ToolUtil.isBlank(userToken)){
throw new Exception("登录超时,请重新登录");
}else{
// 获取请求类型
String requestType = request.getHeader("requestType");
// 判断接口请求类型,如果是手机端请求,需要加上-APP标识
if("2".equals(requestType)){
if(userToken.lastIndexOf(PHONE_TOKEN_SUFFIX) < 0){
userToken += PHONE_TOKEN_SUFFIX;
}
}
}
return userToken;
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import cn.hutool.json.JSONUtil;
import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONObject;
import com.skyeye.common.constans.Constants;
import com.skyeye.common.util.DateUtil;
import com.skyeye.common.util.SpringUtils;
import com.skyeye.common.util.ToolUtil;
import com.skyeye.jedis.JedisClientService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;
public class InputObject extends PutObject implements Serializable{
/**
* @Fields serialVersionUID : 标识
*/
private static final long serialVersionUID = 1L;
public static Set<String> keySet;
private static final String REQUEST_ID_KEY = "request_id_key";
/**
* 网页请求content-type为application/x-www-form-urlencoded
* @throws Exception
*/
public static String setParams() throws Exception{
// 以Map集合存储页面表单传递过来的所有参数的键值对
String sessionKey = getRequest().getParameter("sessionKey");
String method = getRequest().getMethod().toUpperCase();
String contentType = getRequest().getContentType();
if(ObjectConstant.MethodType.POST.getType().equals(method)
|| ObjectConstant.MethodType.DELETE.getType().equals(method)
|| ObjectConstant.MethodType.PUT.getType().equals(method)){
// POST,DELETE,PUT请求
if(!ToolUtil.isBlank(contentType) && contentType.indexOf(Constants.CONENT_TYPE_JSON_REQ) != -1){
// DELETE,PUT请求---json数据请求
return checkParamsByJson(sessionKey);
}else {
// 网页端请求
return checkParamsWebPost(sessionKey);
}
}else if(ObjectConstant.MethodType.GET.getType().equals(method)){
// GET请求
if(!ToolUtil.isBlank(contentType) && contentType.indexOf(Constants.CONENT_TYPE_JSON_REQ) != -1){
// json数据请求
return checkParamsByJson(sessionKey);
}else {
// 网页端请求
return checkParamsWebGet(sessionKey);
}
}
return null;
}
/**
*
* @Title: checkParamsByJson
* @Description: json数据请求
* @param sessionKey
* @return
* @throws Exception
* @return: String
* @throws
*/
private static String checkParamsByJson(String sessionKey) throws Exception{
Map<String, Object> params = getRequestParams();
if(params == null){
String str = GetRequestJsonUtils.getRequestJsonString(getRequest());
try{
Map<String, Object> map = JSONObject.parseObject(str);
return setParamsObjToMapReStr(sessionKey, map);
}catch(Exception e){
Map<String, Object> formMap = ToolUtil.getUrlParams(str);
return setParamsObjToMapReStr(sessionKey, formMap);
}
}
return null;
}
/**
*
* @Title: checkParamsWebPost
* @Description: 网页端请求POST获取
* @param sessionKey
* @return
* @throws Exception
* @return: String
* @throws
*/
private static String checkParamsWebPost(String sessionKey) throws Exception{
// 获取接口API参数信息
List<Map<String, Object>> propertys = (List<Map<String, Object>>) Constants.REQUEST_MAPPING.get(sessionKey).get("list");
// 校验通过的入参集合
Map<String, Object> resultParams = new HashMap<>();
for(Map<String, Object> property : propertys){
// 获取API参数前台传递的key
String key = property.get("id").toString();
// 获取前台传递的value
String value = setDefault((String) getRequest().getParameter(key), property);
// 获取校验条件
String[] ref = property.get("ref").toString().split(",");
// 开始校验
String resultStr = ObjectConstant.containsBoolean(ref, value);
if(!ToolUtil.isBlank(resultStr)){
return String.format(Locale.ROOT, "%s%s%s", "参数:", key, resultStr);
}
resultParams.put(property.get("name").toString(), value);
}
setRequestParams(sessionKey, resultParams);
return null;
}
/**
*
* @Title: checkParamsWebGet
* @Description: 网页端请求GET请求
* @param sessionKey
* @return
* @throws Exception
* @return: String
* @throws
*/
private static String checkParamsWebGet(String sessionKey) throws Exception{
// 获取接口API参数信息
List<Map<String, Object>> propertys = (List<Map<String, Object>>) Constants.REQUEST_MAPPING.get(sessionKey).get("list");
// 校验通过的入参集合
Map<String, Object> resultParams = new HashMap<>();
Map<String, String[]> params = getRequest().getParameterMap();
for(Map<String, Object> property : propertys){
// 获取API参数的key
String key = property.get("id").toString();
// 获取前台传递的value
String value = setDefault(arrayToString(params.get(key)), property);
// 获取校验条件
String[] ref = property.get("ref").toString().split(",");
// 开始校验
String resultStr = ObjectConstant.containsBoolean(ref, value);
if(!ToolUtil.isBlank(resultStr)){
return String.format(Locale.ROOT, "%s%s%s", "参数:", key, resultStr);
}
resultParams.put(property.get("name").toString(), value);
}
setRequestParams(sessionKey, resultParams);
return null;
}
/**
*
* @Title: setDefault
* @Description: 设置默认值
* @param value
* @param property
* @return
* @return: String
* @throws
*/
private static String setDefault(String value, Map<String, Object> property){
// 只有这个值传""时才会设置默认值
if(ToolUtil.isBlank(value) && !ToolUtil.isBlank(property.get("default").toString())){
value = property.get("default").toString();
}
return value;
}
private static String arrayToString(String[] value){
if(value == null){
return "";
}
StringBuffer stb = new StringBuffer();
for(int i = 0; i < value.length; i++){
stb.append(value[i]);
}
return stb.toString();
}
private static String setParamsObjToMapReStr(String sessionKey, Map<String, Object> formMap) throws Exception{
List<Map<String, Object>> propertys = (List<Map<String, Object>>) Constants.REQUEST_MAPPING.get(sessionKey).get("list");
// 校验通过的入参集合
Map<String, Object> resultParams = new HashMap<>();
for(Map<String, Object> property : propertys){
String key = property.get("id").toString();
String value = null;
if(!formMap.containsKey(key)){
value = "";
}else{
value = java.net.URLDecoder.decode(formMap.get(key).toString(), "UTF-8").toString();
}
value = setDefault(value, property);
String[] ref = property.get("ref").toString().split(",");
String resultStr = ObjectConstant.containsBoolean(ref, value);
if(!ToolUtil.isBlank(resultStr)){
return String.format(Locale.ROOT, "%s%s%s", "参数:", key, resultStr);
}
resultParams.put(property.get("name").toString(), value);
}
setRequestParams(sessionKey, resultParams);
return null;
}
private static String getRequestId(){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
HttpServletRequest request = attributes.getRequest();
return String.format(Locale.ROOT, "%s-%s%s-params", sessionId, request.getServletPath(), DateUtil.getTimeStrAndToString());
}
private static void setRequestParams(String sessionKey, Map<String, Object> resultParams) throws Exception{
// 获取唯一id作为该次请求的标识符
String requestId = getRequestId();
getRequest().setAttribute(REQUEST_ID_KEY, requestId);
// 获取用户信息以及其他参数
String allUse = Constants.REQUEST_MAPPING.get(sessionKey).get("allUse").toString();
if("1".equals(allUse) || "2".equals(allUse)){
// 需要登录才能访问
resultParams.put("userToken", GetUserToken.getUserToken(getRequest()));
}
resultParams.put("urlUseJurisdiction", allUse);//URL访问权限参数
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
jedisClient.set(requestId, JSON.toJSONString(resultParams), 10);
}
private static Map<String, Object> getRequestParams(){
String requestId = (String) getRequest().getAttribute(REQUEST_ID_KEY);
if(ToolUtil.isBlank(requestId)){
return null;
}
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
return JSONObject.parseObject(jedisClient.get(requestId));
}
public static Map<String, Object> getMap() throws Exception{
return getRequestParams();
}
public Map<String, Object> getParams() throws Exception {
return getRequestParams();
}
/**
* 获取登录信息
* @return
* @throws Exception
*/
public Map<String, Object> getLogParams() throws Exception {
String userToken = GetUserToken.getUserToken(getRequest());
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
// 用户信息
return JSONUtil.toBean(jedisClient.get("userMation:" + userToken), null);
}
/**
* 获取登录信息
* @return
* @throws Exception
*/
public static Map<String, Object> getLogParamsStatic() throws Exception {
String userToken = GetUserToken.getUserToken(getRequest());
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
// 用户信息
return JSONObject.parseObject(jedisClient.get("userMation:" + userToken));
}
/**
* 获取桌面菜单信息
* @return
* @throws Exception
*/
public List<Map<String, Object>> getLogDeskTopMenuParams() throws Exception {
String userToken = GetUserToken.getUserToken(getRequest());
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
// 桌面菜单信息
return JSONUtil.toList(jedisClient.get("deskTopsMation:" + userToken), null);
}
/**
* 获取所有菜单信息
* @return
* @throws Exception
*/
public List<Map<String, Object>> getLogAllMenuParams() throws Exception {
String userToken = GetUserToken.getUserToken(getRequest());
JedisClientService jedisClient = SpringUtils.getBean(JedisClientService.class);
// 所有菜单信息
return JSONUtil.toList(jedisClient.get("allMenuMation:" + userToken), null);
}
public void removeSession() throws Exception {
getRequest().getSession().invalidate();
}
public Set<String> getKeyForRequestMap(){
return keySet;
}
public static Set<String> getKeySet() {
return keySet;
}
public static void setKeySet(Set<String> keySet) {
InputObject.keySet = keySet;
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class MessageEntity implements Serializable {
private HttpServletRequest request;
private HttpServletResponse response;
public Map<String, Object> object;
public MessageEntity(HttpServletRequest request, HttpServletResponse response){
this.request = request;
this.response = response;
object = new HashMap<>();
setNull();
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public void setNull(){
object.put("returnCode", "-9999");
object.put("error", "0");
object.put("returnMessage", "失败");
object.put("total", 0);
object.put("bean", "");
object.put("rows", "");
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import com.skyeye.common.util.ToolUtil;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public class ObjectConstant {
public static final String CONENT_TYPE_WEB_REQ = "application/x-www-form-urlencoded";//网页请求发送的contentType格式
public static final String CONENT_TYPE_JSON_REQ = "application/json";//json数据请求发送的数据格式
public static final int WRONG = -9999;
public static final String WRONG_MESSAGE = "失败";
public static enum MethodType {
POST("POST"),
GET("GET"),
DELETE("DELETE"),
PUT("PUT");
private String type;
MethodType(String type){
this.type = type;
}
public String getType() {
return type;
}
}
public static enum VerificationParams {
REQUIRED("required", "参数非空校验", "不能为空", "isBlank", ""),
NUM("num", "数字校验", "数字类型不正确", "regularCheck",
"[0-9]*"),
DATE("date", "时间校验,格式:yyyy-MM-dd HH:mm:ss", "时间类型不正确", "isDate", ""),
EMAIL("email", "邮箱校验", "邮箱类型不正确", "regularCheck",
"^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"),
IDCARD("idcard", "证件号校验", "证件号类型不正确", "regularCheck",
"(^\\d{18}$)|(^\\d{15}$)"),
PHONE("phone", "手机号校验", "手机号类型不正确", "regularCheck",
"^((13[0-9])|(15[^4])|(19[0-9])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$"),
URL("url", "url校验", "url类型不正确", "regularCheck",
"http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"),
IP("ip", "ip校验", "ip类型不正确", "regularCheck",
getIpRegex()),
POSTCODE("postcode", "国内邮编校验", "国内邮编类型不正确", "regularCheck",
"^\\d{6}$"),
DOUBLE("double", "验证小数点后两位,一般用于金钱校验", "小数格式类型不正确", "regularCheck",
"^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"),
JSON("json", "json字符串校验", "参数类型非json", "isJson", "");
private String key;
private String desc;
private String resultMsg;
private String method;
private String regular;
VerificationParams(String key, String desc, String resultMsg, String method,
String regular){
this.key = key;
this.desc = desc;
this.resultMsg = resultMsg;
this.method = method;
this.regular = regular;
}
public static String getMethod(String str){
for (VerificationParams q : VerificationParams.values()){
if(q.getKey().equals(str)){
return q.getMethod();
}
}
return "";
}
public static String getResultMsg(String str){
for (VerificationParams q : VerificationParams.values()){
if(q.getKey().equals(str)){
return q.getResultMsg();
}
}
return "";
}
public static String getRegular(String str){
for (VerificationParams q : VerificationParams.values()){
if(q.getKey().equals(str)){
return q.getRegular();
}
}
return "";
}
public static List<Map<String, Object>> getList(){
List<Map<String, Object>> beans = new ArrayList<>();
for (VerificationParams q : VerificationParams.values()){
Map<String, Object> bean = new HashMap<>();
bean.put("key", q.getKey());
bean.put("value", q.getDesc());
beans.add(bean);
}
return beans;
}
public String getKey() {
return key;
}
public String getDesc() {
return desc;
}
public String getMethod() {
return method;
}
public String getResultMsg() {
return resultMsg;
}
public String getRegular() {
return regular;
}
}
/**
*
* @Title: getIpRegex
* @Description: 获取ip校验的正则
* @return
* @return: String
* @throws
*/
public static String getIpRegex(){
String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
return "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
}
/**
*
* @Title: regularCheck
* @Description: 字符串类型校验
* @param str 字符串
* @param regular 正则表达式
* @return 如果符合正则,则返回true,否则返回false
* @return: boolean
* @throws
*/
public boolean regularCheck(String str, String regular){
Pattern pattern = Pattern.compile(regular);
return pattern.matcher(str).matches();
}
public boolean isBlank(String str, String regular){
return !ToolUtil.isBlank(str);
}
public boolean isDate(String str, String regular){
return ToolUtil.isDate(str);
}
public boolean isJson(String str, String regular) { return ToolUtil.isJson(str); }
/**
*
* @Title: containsBoolean
* @Description: 请求xml参数判断
* @param ref
* @param str
* @param @return 参数
* @return String 返回类型
* @throws
*/
public static String containsBoolean(String[] ref, String str){
for(String key: ref){
if(ToolUtil.isBlank(key)){
continue;
}
if(!key.equals(VerificationParams.REQUIRED.getKey())){
// 不是非空校验的需要加上非空处理
if(ToolUtil.isBlank(str)){
continue;
}
}
try {
String methodStr = VerificationParams.getMethod(key);
if(!ToolUtil.isBlank(methodStr)){
String regex = VerificationParams.getRegular(key);
boolean result = (boolean) getResult(methodStr, str, regex);
if(!result){
return VerificationParams.getResultMsg(key);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
*
* @Title: getResult
* @Description: 通过反射的手法获取方法校验结果
* @param methodStr 方法名
* @param params 参数,支持多个
* @return
* @throws Exception
* @return: Object
* @throws
*/
@SuppressWarnings("rawtypes")
private static Object getResult(String methodStr, Object... params) throws Exception{
Class<?> classType = Class.forName(ObjectConstant.class.getName());
Class[] argTypes = new Class[2];
argTypes[0] = String.class;
argTypes[1] = String.class;
Method method = ObjectConstant.class.getMethod(methodStr, argTypes);
return method.invoke(classType.newInstance(), params);
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import cn.hutool.json.JSONUtil;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OutputObject extends PutObject implements Serializable{
/**
* @Fields serialVersionUID : 标识
*/
private static final long serialVersionUID = 1L;
public void settotal(Object total){
getModelEntity().object.put("total", total);
}
public void setreturnMessage(Object returnMessage){
getModelEntity().object.put("returnMessage", returnMessage);
}
public void setreturnMessage(Object returnMessage, Object returnCode) throws Exception{
setreturnMessage(returnMessage);
setreturnCode(returnCode);
}
public void setreturnCode(Object returnCode){
getModelEntity().object.put("returnCode", returnCode);
}
public void setErroCode(int code){
getModelEntity().object.put("error", code);
}
public void setCustomBean(String key, Map<String,Object> bean) throws Exception {
getModelEntity().object.put(key, bean);
}
public void setCustomBeans(String key, List<Map<String,Object>> bean) throws Exception {
getModelEntity().object.put(key, bean);
}
public void setBean(Map<String,Object> bean) throws Exception {
getModelEntity().object.put("bean", bean);
}
public void setBeans(List<Map<String,Object>> beans) throws Exception {
getModelEntity().object.put("rows", beans);
}
public static void setCode(int code){
getModelEntity().object.put("returnCode", code);
}
public static void setMessage(String Message){
if(getModelEntity().object != null){
getModelEntity().object.put("returnMessage", Message);
}
}
public static int getCode(){
if(getModelEntity().object == null){
getModelEntity().object = new HashMap<>();
}
return Integer.parseInt(getModelEntity().object.get("returnCode").toString());
}
public static String getMessage(){
return getModelEntity().object.get("returnMessage").toString();
}
public static void put(){
Object context = JSONUtil.toJsonStr(getModelEntity().object);
PrintWriter out = null;
getResponse().setCharacterEncoding("UTF-8");
getResponse().setContentType("text/html;charset=UTF-8");
try {
out = getResponse().getWriter();// 获取输入流
if(out != null){
out.print(context);// 将信息发送到前台
out.flush();// 刷新
}
} catch (Exception e) {
} finally {
if(out != null){
out.close();// 关闭输入流
}
}
}
public Map<String, Object> getObject() {
return getModelEntity().object;
}
public void setObject(Map<String, Object> map) {
getModelEntity().object = map;
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.object;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
public class PutObject implements Serializable{
/**
* @Fields serialVersionUID : 标识
*/
private static final long serialVersionUID = 1L;
private static ThreadLocal<MessageEntity> model = new ThreadLocal<MessageEntity>();
public PutObject(){
}
public PutObject(HttpServletRequest request, HttpServletResponse response){
model.set(new MessageEntity(request, response));
}
public static HttpServletRequest getRequest() {
if(model.get() == null){
return null;
}
return model.get().getRequest();
}
public static HttpServletResponse getResponse() {
return model.get().getResponse();
}
public static void remove() {
model.remove();
}
public static MessageEntity getModelEntity(){
return model.get();
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
*
* @ClassName: CalculationUtil
* @Description: 精确计算工具类(加,减,乘,除,返回较大值,返回较小值)
* @author: skyeye云系列--卫志强
* @date: 2021/7/7 22:00
*
* @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved.
* 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的
*/
public class CalculationUtil {
/**
* 提供精确加法计算的add方法
*/
public static String add(String value1, String value2) {
return add(value1, value2, 0, 0);
}
/**
* 提供精确加法计算的add方法(默認四捨五入)
* @param value1 被加数
* @param value2 加数
* @param scale 精确范围(小数点后几位)
*/
public static String add(String value1, String value2, int scale) {
return add(value1, value2, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* 提供精确加法计算的add方法(默認四捨五入)
*
* @param scale 精确范围(小数点后几位)
* @param values 加数
* @return
*/
public static String add(int scale, String... values) {
if(values.length == 1){
return values[0];
}
String result = values[0];
for (int i = 1; i < values.length; i++){
result = add(result, values[i], scale);
}
return result;
}
/**
* 提供精确加法计算的add方法
* @param value1 被加数
* @param value2 加数
* @param scale 精确范围(小数点后几位)
* @param mode 精確模式
*/
public static String add(String value1, String value2, int scale, int mode) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.add(b2);
// mode为0,则不需要精确
if (mode != 0) {
result = result.setScale(scale, mode);
}
return result.toString();
}
public static int compareTo(String value1, String value2, int scale, int mode) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.subtract(b2);
// mode为0,则不需要精确
if (mode != 0) {
result = result.setScale(scale, mode);
}
return result.compareTo(BigDecimal.ZERO);
}
/**
* 提供精确的除法运算方法divide
* @param value1 被除数
* @param value2 除数
*/
public static String divide(String value1, String value2) throws IllegalAccessException {
return divide(value1, value2, 0, null);
}
/**
* 提供精确的除法运算方法divide(默認四捨五入)
* @param value1 被除数
* @param value2 除数
* @param scale 精确范围(小数点后几位)
*/
public static String divide(String value1, String value2, int scale) throws IllegalAccessException {
return divide(value1, value2, scale, RoundingMode.HALF_UP);
}
/**
* 提供精确的除法运算方法divide
*
* @param value1 被除数
* @param value2 除数
* @param scale 精确范围(小数点后几位)
* @param roundingMode 精確模式
*/
public static String divide(String value1, String value2, int scale, RoundingMode roundingMode)
throws IllegalAccessException {
// 如果精确范围小于0,抛出异常信息
if (scale < 0) {
throw new IllegalAccessException("精确度不能小于0");
}
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
// roundingMode为null,则不需要精确
if (roundingMode != null) {
return new Double(b1.divide(b2, scale, roundingMode).doubleValue()).toString();
} else {
return new Double(b1.divide(b2).doubleValue()).toString();
}
}
/**
* 比较大小 :返回较大的那个
*/
public static String getMax(String value1, String value2, int scale) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.max(b2);
result = result.setScale(scale, BigDecimal.ROUND_HALF_UP);
return result.toString();
}
/**
* 比较大小 :返回较小的那个
*/
public static String getMin(String value1, String value2, int scale) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.min(b2);
result = result.setScale(scale, BigDecimal.ROUND_HALF_UP);
return result.toString();
}
/**
*
* 提供精确乘法运算的multiply方法
* @param value1 被乘数
* @param value2 乘数
* @return 两个参数的积
*/
public static String multiply(String value1, String value2) {
return multiply(value1, value2, 0, 0);
}
/**
* 提供精确乘法运算的multiply方法(默認四捨五入)
* @param value1 被乘数
* @param value2 乘数
* @param scale 精确范围(小数点后几位)
*/
public static String multiply(String value1, String value2, int scale) {
return multiply(value1, value2, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* 提供精确乘法运算的multiply方法(默認四捨五入)
*
* @param scale 精确范围(小数点后几位)
* @param values 乘数
* @return
*/
public static String multiply(int scale, String... values) {
if(values.length == 1){
return values[0];
}
String result = values[0];
for (int i = 1; i < values.length; i++){
result = multiply(result, values[i], scale);
}
return result;
}
/**
* 提供精确乘法运算的multiply方法
* @param value1 被乘数
* @param value2 乘数
* @param scale 精确范围(小数点后几位)
* @param mode 精確模式
*/
public static String multiply(String value1, String value2, int scale, int mode) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.multiply(b2);
// mode为0,则不需要精确
if (mode != 0) {
result = result.setScale(scale, mode);
}
return result.toString();
}
/**
* 提供精确减法运算的subtract方法
* @param value1 被减数
* @param value2 减数
* @return 两个参数的差
*/
public static String subtract(String value1, String value2) {
return subtract(value1, value2, 0, 0);
}
/**
* 提供精确减法运算的subtract方法(默認四捨五入)
* @param value1 被减数
* @param value2 减数
* @param scale 精确范围(小数点后几位)
*/
public static String subtract(String value1, String value2, int scale) {
return subtract(value1, value2, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* 提供精确减法运算的subtract方法
* @param value1 被减数
* @param value2 减数
* @param scale 精确范围(小数点后几位)
* @param mode 精確模式
*/
public static String subtract(String value1, String value2, int scale, int mode) {
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
BigDecimal result = b1.subtract(b2);
// mode为0,则不需要精确
if (mode != 0) {
result = result.setScale(scale, mode);
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(subtract("100", "-10", 2));
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @ClassName: DateUtil
* @Description: 日期工具类
* @author: skyeye云系列--卫志强
* @date: 2021/7/6 22:06
* @Copyright: 2021 https://gitee.com/doc_wei01/skyeye Inc. All rights reserved.
* 注意:本内容仅限购买后使用.禁止私自外泄以及用于其他的商业目的
*/
public class DateUtil {
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYYY_MM = "yyyy-MM";
public static final String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String HH_MM_SS = "HH:mm:ss";
public static final String HH_MM = "HH:mm";
public static String getTimeAndToString() {
return getPointTime(YYYY_MM_DD_HH_MM_SS);
}
public static String getTimeIsYMD() {
return getPointTime(YYYYMMDD);
}
public static String getTimeStrAndToString() {
return getPointTime(YYYYMMDDHHMMSSSSS);
}
public static String getYmdTimeAndToString() {
return getPointTime(YYYY_MM_DD);
}
public static String getHmsTimeAndToString() {
return getPointTime(HH_MM_SS);
}
/**
* 获取两个日期之间的所有日期(包含最后一天)
*
* @param startTime 开始日期
* @param endTime 结束日期
* @return 所有日期(包含最后一天)
*/
public static List<String> getDays(String startTime, String endTime) {
// 返回的日期集合
List<String> days = new ArrayList<String>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(getPointTime(startTime, YYYY_MM_DD));
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(getPointTime(endTime, YYYY_MM_DD));
// 日期加1(包含结束)
tempEnd.add(Calendar.DATE, +1);
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 将日期转化为正常的年月日时分秒
*
* @param timeStmp
* @return
*/
public static String getDateStr(long timeStmp) {
SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
return dateFormat.format(new Date(timeStmp));
}
/**
* 转化cron
*
* @param date date
* @param foramt foramt
* @return
*/
public static int getTime(Date date, String foramt) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ("y".equals(foramt)) {
return cal.get(Calendar.YEAR);// 获取年份
} else if ("M".equals(foramt)) {
return cal.get(Calendar.MONTH) + 1;// 获取月
} else if ("d".equals(foramt)) {
return cal.get(Calendar.DAY_OF_MONTH);// 获取日
} else if ("H".equals(foramt)) {
return cal.get(Calendar.HOUR_OF_DAY);// 获取时
} else if ("m".equals(foramt)) {
return cal.get(Calendar.MINUTE);// 获取分
} else if ("s".equals(foramt)) {
return cal.get(Calendar.SECOND);// 获取秒
} else {
return -1;
}
}
/**
* 获取指定日期 前/后n天|分钟的日期
*
* @param date 日期
* @param n N天/分钟
* @param format 标识:d代表天,m代表分钟
* @return
*/
public static Date getAfDate(Date date, int n, String format) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
if ("d".equals(format)) {
calendar.add(Calendar.DAY_OF_MONTH, n);// 天
} else if ("m".equals(format)) {
calendar.add(Calendar.MINUTE, n);// 分钟
}
date = calendar.getTime();
return date;
}
/**
* 计算两个日期相差多少天
*
* @param startDate 开始日期 yyyy-MM-dd/yyyy-MM-dd HH:mm:ss
* @param endDate 结束日期 yyyy-MM-dd/yyyy-MM-dd HH:mm:ss
* @return
* @throws ParseException
*/
public static int getDistanceDay(String startDate, String endDate) throws ParseException{
Calendar cal = Calendar.getInstance();
// 开始日期
cal.setTime(getPointTime(startDate, YYYY_MM_DD));
long time1 = cal.getTimeInMillis();
// 结束日期
cal.setTime(getPointTime(endDate, YYYY_MM_DD));
long time2 = cal.getTimeInMillis();
// 计算
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 两个时间之间相差距离多少分
*
* @param str1 时间参数 1,格式:yyyy-MM-dd HH:mm:ss:
* @param str2 时间参数 2,格式:yyyy-MM-dd HH:mm:ss:
* @return 相差天数
*/
public static long getDistanceMinute(String str1, String str2) throws Exception {
long min = 0;
try {
Date one = getPointTime(str1, YYYY_MM_DD_HH_MM_SS);
Date two = getPointTime(str2, YYYY_MM_DD_HH_MM_SS);
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
min = diff / (1000 * 60);
} catch (ParseException e) {
e.printStackTrace();
}
return min;
}
/**
* 两个时间之间相差距离多少时分秒
*
* @param str1 时间参数 1:
* @param str2 时间参数 2:
* @return 相差时分秒数
*/
public static String getDistanceHMS(String str1, String str2) throws Exception {
long diff = getDistanceMillisecondHMS(str1, str2);
long hour = diff / (1000 * 60 * 60);
long minute = (diff - hour * 60 * 60 * 1000) / (1000 * 60);
long second = (diff - hour * 60 * 60 * 1000 - minute * 60 * 1000) / 1000;
return hour + ":" + minute + ":" + second;
}
/**
* 两个时间之间相差距离多少分钟
*
* @param str1 时间参数 1,格式:HH:mm:ss
* @param str2 时间参数 2,格式:HH:mm:ss
* @return 相差分钟
* @throws Exception
*/
public static String getDistanceMinuteByHMS(String str1, String str2) throws Exception {
long diff = getDistanceMillisecondHMS(str1, str2);
return CalculationUtil.divide(
String.valueOf(diff),
CalculationUtil.multiply("1000", "60", 2), 2);
}
/**
* 两个时间之间相差距离多少毫秒
*
* @param str1 时间参数 1:
* @param str2 时间参数 2:
* @return 相差毫秒
* @throws Exception
*/
public static long getDistanceMillisecondHMS(String str1, String str2) throws Exception {
try {
Date one = getPointTime(str1, HH_MM_SS);
Date two = getPointTime(str2, HH_MM_SS);
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
return diff;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 时间字符串比较大小,字符串格式为:yyyy-MM-dd hh:mm:ss
*
* @param time1 日期1
* @param time2 日期2
* @return 日期1早于日期2,返回true,反之返回false
* @throws ParseException
*/
public static boolean compare(String time1, String time2) throws ParseException {
return compareTime(time1, time2, YYYY_MM_DD_HH_MM_SS);
}
/**
* 时间字符串比较大小,字符串格式为:HH:mm
*
* @param time1 日期1
* @param time2 日期2
* @return 日期1早于日期2,返回true,反之返回false
* @throws ParseException
*/
public static boolean compareTime(String time1, String time2) throws ParseException {
return compareTime(time1, time2, HH_MM);
}
/**
* 时分秒字符串比较大小,字符串格式为:HH:mm:ss
*
* @param time1 日期1
* @param time2 日期2
* @return 日期1早于日期2,返回true,反之返回false
* @throws ParseException
*/
public static boolean compareTimeHMS(String time1, String time2) throws ParseException {
return compareTime(time1, time2, HH_MM_SS);
}
public static boolean compareTime(String time1, String time2, String pattern) throws ParseException {
Date t1 = getPointTime(time1, pattern);
Date t2 = getPointTime(time2, pattern);
// Date类的一个方法,如果t1早于t2返回true,否则返回false
if (!t1.after(t2)) {
return true;
} else {
return false;
}
}
/**
* 比较时分时间段是否有重复
*
* @param list ->[08:00-09:00,13:00-16:30]
* @return true:有重复;false:没有重复
* @throws ParseException
*/
public static boolean checkOverlap(List<String> list) throws ParseException {
// 排序ASC
Collections.sort(list);
// 是否重叠标识
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
// 跳过第一个时间段不做判断
String[] itime = list.get(i).split("-");
for (int j = (i + 1); j < list.size(); j++) {
// 如果当前遍历的i开始时间小于j中某个时间段的结束时间那么则有重叠,反之没有重叠
String[] jtime = list.get(j).split("-");
// 此处compare为日期比较(返回true:date1小/相等、返回false:date1大)
boolean compare = compare((DateUtil.getYmdTimeAndToString() + " " + itime[1] + ":00"),
(DateUtil.getYmdTimeAndToString() + " " + jtime[0] + ":00"));
if (!compare) {
flag = true;
// 只要存在一个重叠则可退出内循环
break;
}
}
// 当标识已经认为重叠了则可退出外循环
if (flag) {
break;
}
}
return flag;
}
/**
* 获取上个月的年月,格式yyyy-MM
*
* @return
*/
public static String getLastMonthDate() {
SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM);
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
return sdf.format(cal.getTime());
}
/**
* 获取某年某月的所有日期(yyyy-mm-dd格式字符串)
*
* @param year 年
* @param month 月
* @return 所有日期
*/
public static List<String> getMonthFullDay(int year, int month) {
SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat(YYYY_MM_DD);
List<String> fullDayList = new ArrayList<>(32);
// 获得当前日期对象
Calendar cal = Calendar.getInstance();
// 清除信息
cal.clear();
cal.set(Calendar.YEAR, year);
// 1月从0开始
cal.set(Calendar.MONTH, month - 1);
// 当月1号
cal.set(Calendar.DAY_OF_MONTH, 1);
int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int j = 1; j <= count; j++) {
fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 1);
}
return fullDayList;
}
/**
* 获取指定月后N个月的月份日期(包含指定月)
*
* @param yearMonth 指定月,格式为yyyy-MM
* @return List<String>
* @throws Exception
*/
public static List<String> getPointMonthAfterMonthList(String yearMonth, int n) throws Exception {
List<String> list = new ArrayList<>();
list.add(yearMonth);
for(int i = 1; i <= n; i++){
// 获取往后的日期
list.add(getSpecifiedDayMation(yearMonth, YYYY_MM, 1, i, 10));
}
return list;
}
/**
* 判断指定日期(yyyy-MM-dd)是周几
*
* @param dates 指定日期
* @return 周几
* @throws ParseException
*/
public static int getWeek(String dates) throws ParseException {
Calendar cal = Calendar.getInstance();
Date d = getPointTime(dates, YYYY_MM_DD);
cal.setTime(d);
int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (weekDay == 0){
weekDay = 7;
}
return weekDay;
}
/**
* 判断指定日期(yyyy-MM-dd)是单周还是双周
*
* @param dates 指定日期
* @return 1是双周,0是单周
*/
public static int getWeekType(String dates) throws ParseException {
Calendar cal = Calendar.getInstance();
Date d = getPointTime(dates, YYYY_MM_DD);
cal.setTime(d);
int weekNum = cal.get(Calendar.WEEK_OF_YEAR);
if(weekNum % 2 == 0){
// 双周
return 1;
}else{
// 单周
return 0;
}
}
/**
* 获取指定月份的所有日期
*
* @param months 月份集合,格式为yyyy-MM
* @return
*/
public static List<String> getDaysByMonths(List<String> months){
List<String> monthDays = new ArrayList<>();
for (String month: months){
monthDays.addAll(DateUtil.getMonthFullDay(Integer.parseInt(month.split("-")[0]), Integer.parseInt(month.split("-")[1])));
}
return monthDays;
}
/**
* 获取当前时间戳
* @return
*/
public static long getTimeStampAndToString() {
return System.currentTimeMillis();
}
/**
* 根据指定时间获取各种时间之后的时间
*
* @param dateStr 指定时间
* @param dateType 时间格式:yyyy-MM-dd hh:mm:ss
* @param beforeOrAfter 往前计算还是往后计算 0:时间往前推;1:时间往后推
* @param num 时间长度
* @param remindType 往前计算或者往后计算是按照天还是小时还是分钟计算[1,2,3,4]:分钟;[5,6]:小时;[7,8,9]:天;[10]:月
* @return 计算后的日期
* @throws Exception
*/
public static String getSpecifiedDayMation(String dateStr, String dateType, int beforeOrAfter, int num, int remindType) throws Exception{
Calendar c = Calendar.getInstance();
c.setTime(getPointTime(dateStr, dateType));
if(beforeOrAfter == 0)
num = -num;
if(remindType == 1 || remindType == 2 || remindType == 3 || remindType == 4){
// 分钟
c.add(Calendar.MINUTE, num);
}else if(remindType == 5 || remindType == 6){
// 小时
c.add(Calendar.HOUR_OF_DAY, num);
}else if(remindType == 7 || remindType == 8 || remindType == 9){
// 天
c.add(Calendar.DAY_OF_MONTH, num);
}else if(remindType == 10){
// 月
c.add(Calendar.MONTH, num);
}else{
return null;
}
String dayAfter = new SimpleDateFormat(dateType).format(c.getTime());
return dayAfter;
}
/**
* 获取指定格式的日期字符串
*
* @param pattern 格式
* @return 日期字符串
*/
public static String getPointTime(String pattern){
Date dt = new Date();
DateFormat df = new SimpleDateFormat(pattern);
String nowTime = df.format(dt);
return nowTime;
}
/**
* 获取指定格式以及指定日期对象
* @param time 指定日期
* @param pattern 指定格式
* @return 日期对象
* @throws ParseException
*/
public static Date getPointTime(String time, String pattern) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.parse(time);
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.common.util;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*
* @author 卫志强
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext = null;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
SpringUtils.beanFactory = beanFactory;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws org.springframework.beans.BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException {
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
* 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*
* @param name
* @return boolean
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
*
* @param name
* @return
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return beanFactory.getAliases(name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
}
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.jedis;
import redis.clients.util.Slowlog;
import java.util.List;
public interface JedisClientService {
/**
*
* @Title: logEmpty
* @Description: 清空日志
* @param @return
* @throws Exception 参数
* @return String 返回类型
* @throws
*/
String logEmpty(String ip);
/**
*
* @Title: set
* @Description: Redis SET命令用于在Redis键中设置一些字符串值
* @param key
* @param value
* @param @return 参数
* @return String 返回类型
* @throws
*/
void set(String key, String value);
/**
*
* @Title: set
* @Description: Redis SET命令用于在Redis键中设置一些字符串值
* @param key
* @param value
* @param seconds 过期时间,单位:秒
* @return void 返回类型
* @throws
*/
void set(String key, String value, int seconds);
/**
*
* @Title: get
* @Description: 根据key去查询相应的值
* @param key
* @param @return 参数
* @return String 返回类型
* @throws
*/
String get(String key);
/**
*
* @Title: exists
* @Description: 判断key在Redis缓存中是否存在
* @param key
* @param @return 参数
* @return Boolean 返回类型
* @throws
*/
Boolean exists(String key);
/**
*
* @Title: expire
* @Description: 设置key的过期时间
* @param key
* @param seconds 单位:秒
* @param @return 参数
* @return Long 返回类型
* @throws
*/
boolean expire(String key, int seconds);
/**
*
* @Title: incrByData
* @Description: Redis Incr 命令将 key 中储存的数字值增idata
* @param key
* @param @return 参数
* @return Long 返回类型
* @throws
*/
Long incrByData(String key, long idata);
/**
*
* @Title: del
* @Description: 删除给定的一个 key 不存在的 key 会被忽略。
* @param key
* @param @return 参数
* @return Long 返回类型
* @throws
*/
boolean del(String key);
/**
*
* @Title: getLogs
* @Description: 获取日志列表
* @param entries
* @param @return
* @throws Exception 参数
* @return List<Slowlog> 返回类型
* @throws
*/
List<Slowlog> getLogs(long entries);
/**
*
* @Title: getLogsLen
* @Description: 获取日志条数
* @param @return
* @throws Exception 参数
* @return Long 返回类型
* @throws
*/
Long getLogsLen();
/**
*
* @Title: logEmpty
* @Description: 清空日志
* @param @return
* @throws Exception 参数
* @return String 返回类型
* @throws
*/
String logEmpty();
/**
*
* @Title: dbSize
* @Description: 获取占用内存大小
* @param @return
* @throws Exception 参数
* @return Long 返回类型
* @throws
*/
Long dbSize();
/**
*
* @Title: delKeys
* @Description: 根据前缀进行删除
* @param @return
* @throws Exception 参数
* @return Long 返回类型
* @throws
*/
void delKeys(String keysPattern);
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.jedis.impl;
import com.skyeye.common.constans.RedisConstants;
import com.skyeye.common.util.ToolUtil;
import com.skyeye.jedis.JedisClientService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.util.Slowlog;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
*
* @ClassName: JedisClientCluster
* @Description: redis集群
* @author 卫志强
* @date 2018年11月17日
*
*/
@Service
public class JedisClientServiceImpl implements JedisClientService {
private RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public RedisTemplate getRedisTemplate() {
return this.redisTemplate;
}
@Override
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
// 为防止缓存穿透,空值设置过期时间,2S后自动删除
if(ToolUtil.isBlank(value)){
expire(key, 2);
}else{
expire(key, RedisConstants.TEN_DAY_SECONDS);
}
}
@Override
public void set(String key, String value, int seconds) {
redisTemplate.opsForValue().set(key, value);
// 为防止缓存穿透,空值设置过期时间,2S后自动删除
if(ToolUtil.isBlank(value)){
expire(key, 2);
}else{
expire(key, seconds);
}
}
@Override
public String get(String key) {
return (String) redisTemplate.opsForValue().get(key);
}
@Override
public Boolean exists(String key) {
return redisTemplate.hasKey(key);
}
@Override
public boolean expire(String key, int seconds) {
return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
}
@Override
public Long incrByData(String key, long idata) {
return redisTemplate.opsForValue().increment(key, idata);
}
@Override
public boolean del(String key) {
return redisTemplate.delete(key);
}
@Override
public void delKeys(String keysPattern) {
Set<String> keys = redisTemplate.keys(keysPattern);
redisTemplate.delete(keys);
}
@Override
public List<Slowlog> getLogs(long entries) {
return null;
}
@Override
public Long getLogsLen() {
return new Long(1);
}
@Override
public String logEmpty() {
return "";
}
@Override
public Long dbSize() {
return new Long(1);
}
@Override
public String logEmpty(String ip) {
return null;
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.jedis.util;
import com.skyeye.common.util.ToolUtil;
import com.skyeye.jedis.impl.JedisClientServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.KeyGenerator;
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.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
@Configuration
public class JedisClusterConfig {
@Autowired
private RedisProperties redisProperties;
private static final Logger logger = LoggerFactory.getLogger(JedisClusterConfig.class);
// 是否开启集群 true:是 false:否
@Value("${spring.redis.isJq}")
private boolean isJq;
/**
* JedisPoolConfig 连接池
* @return
*/
@Bean(name = "jedisPoolConfig")
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空闲连接数
jedisPoolConfig.setMaxIdle(500);
// 最小空闲连接数
jedisPoolConfig.setMinIdle(20);
// 最大连接数
jedisPoolConfig.setMaxTotal(800);
jedisPoolConfig.setBlockWhenExhausted(true);
jedisPoolConfig.setTestOnBorrow(true);
// Idle时进行连接扫描
jedisPoolConfig.setTestWhileIdle(true);
// 表示idle object evitor每次扫描的最多的对象数
jedisPoolConfig.setNumTestsPerEvictionRun(10);
// 表示idle object evitor两次扫描之间要sleep的毫秒数
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
// 表示一个对象至少停留在idle状态的最短时间,然后才能被idle object
// evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);
jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(60000);
// 最大阻塞等待时间,负值为无限制
jedisPoolConfig.setMaxWaitMillis(10000);
return jedisPoolConfig;
}
@Bean(name = "redisClusterConfiguration")
public RedisClusterConfiguration getRedisClusterConfiguration() {
RedisClusterConfiguration configuration = new RedisClusterConfiguration();
Set<RedisNode> nodes = new HashSet<>();
String[] serverArray = redisProperties.getCluster().split(",");
for (String ipPort : serverArray) {
String hostName = ipPort.split(":")[0];
int port = Integer.parseInt(ipPort.split(":")[1]);
RedisNode node = new RedisNode(hostName, port);
nodes.add(node);
}
configuration.setClusterNodes(nodes);
return configuration;
}
/**
* 单机版和集群版配置
* @Title: JedisConnectionFactory
* @param @param jedisPoolConfig
* @param @return
* @return JedisConnectionFactory
* @autor lpl
* @date 2018年2月24日
* @throws
*/
@Bean(name = "jedisConnectionFactory")
public JedisConnectionFactory jedisConnectionFactory(
@Qualifier("jedisPoolConfig") JedisPoolConfig jedisPoolConfig,
@Qualifier("redisClusterConfiguration") RedisClusterConfiguration redisClusterConfiguration) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
// 是否开启集群模式
if (isJq) {
// 集群模式
jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
} else {
// 单机模式
jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
// IP地址
jedisConnectionFactory.setHostName(redisProperties.getSingleHost());
// 端口号
jedisConnectionFactory.setPort(redisProperties.getSinglePort());
}
// 判断密码是否存在,存在设置值
checkPasswordIfNull(jedisConnectionFactory);
return jedisConnectionFactory;
}
/**
* 校验password是否为空,不为空设置密码
* @param jedisConnectionFactory
*/
private void checkPasswordIfNull(JedisConnectionFactory jedisConnectionFactory) {
if (!ToolUtil.isBlank(redisProperties.getPassword())) {
jedisConnectionFactory.setPassword(redisProperties.getPassword());
}
}
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean(name = "redisTemplate")
public RedisTemplate getRedisTemplate(
@Qualifier("jedisConnectionFactory") JedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// 设置序列化Key的实例化对象
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 设置序列化Value的实例化对象
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean(name = "jedisClientServiceImpl")
public JedisClientServiceImpl getJedisCluster(RedisTemplate redisTemplate){
JedisClientServiceImpl jedisClientServiceImpl = new JedisClientServiceImpl();
jedisClientServiceImpl.setRedisTemplate(redisTemplate);
return jedisClientServiceImpl;
}
/**
* 自定义缓存时,keyGenerator 的生成规则
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理缓存
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 更改值的序列化方式,否则在Redis可视化软件中会显示乱码。默认为JdkSerializationRedisSerializer
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer());
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair) // 设置序列化方式
.entryTtl(Duration.ofHours(1)); // 设置过期时间
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
.cacheDefaults(defaultCacheConfig).build();
}
}
/*******************************************************************************
* Copyright 卫志强 QQ:598748873@qq.com Inc. All rights reserved. 开源地址:https://gitee.com/doc_wei01/skyeye
******************************************************************************/
package com.skyeye.jedis.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* 读取redis配置信息并装载
*
* @author 卫志强
*
*/
@Component
@Data
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {
private int expireSeconds;
private String cluster;
private int commandTimeout;
private String password;
// 单机版参数
@Value("${redis.single.host}")
private String singleHost;
@Value("${redis.single.port}")
private int singlePort;
}
......@@ -21,8 +21,6 @@
<groupId>com.skyeye</groupId>
<artifactId>skyeye-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${basedir}/lib/skyeye-base-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
<!-- Springboot整合Nutz,Nutz可以用于自定义事务,例如:Trans.begin(); -->
......
#Created by Apache Maven 3.2.1
version=0.0.1-SNAPSHOT
groupId=com.skyeye
artifactId=skyeye-entity
E:\skyeye\skyeye-promote\skyeye-entity\src\main\java\com\skyeye\quartz\entity\SysQuartz.java
E:\skyeye\skyeye-promote\skyeye-entity\src\main\java\com\skyeye\common\pojo\SearchResult.java
E:\skyeye\skyeye-promote\skyeye-entity\src\main\java\com\skyeye\common\pojo\Item.java
E:\skyeye\skyeye-promote\skyeye-entity\src\main\java\com\skyeye\common\pojo\SearchItem.java
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册