Initial commit

This commit is contained in:
Carol 2019-07-26 15:12:03 +08:00
commit ded76d7f46
28 changed files with 3819 additions and 0 deletions

2
.gitattributes vendored Normal file
View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

6
.idea/encodings.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$" charset="UTF-8" />
</component>
</project>

14
.idea/misc.xml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

515
.idea/workspace.xml Normal file
View File

@ -0,0 +1,515 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ChangeListManager">
<list default="true" id="eb22885f-8347-4349-9d11-17e6e18e8973" name="Default" comment="" />
<ignored path="$PROJECT_DIR$/out/" />
<ignored path="$PROJECT_DIR$/target/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="TRACKING_ENABLED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileEditorManager">
<leaf>
<file leaf-file-name="pom.xml" pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/pom.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="377">
<caret line="218" column="29" selection-start-line="218" selection-start-column="29" selection-end-line="218" selection-end-column="29" />
</state>
</provider>
</entry>
</file>
</leaf>
</component>
<component name="FindInProjectRecents">
<findStrings>
<find>rightPush</find>
<find>fastjson</find>
</findStrings>
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/util/domain/redis/Receiver.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/util/config/RedisConfig.java" />
<option value="$PROJECT_DIR$/src/main/java/cn/migu/log/utils/config/RedisConfig.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/RedisConfig.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/AsyncExecutePool.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/AsyncThreadPoolConfig.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/RedisUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/ElasticsearchConfig.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/RestTemplateConfig.java" />
<option value="$PROJECT_DIR$/pom.xml" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/DataResult.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/LogUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/DateUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/FileEncryptDecrypt.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/FileUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/GracefulShutdown.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/HttpCommonUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/LoggerUtil.java" />
<option value="$PROJECT_DIR$/src/main/java/site/cnkj/utils/RestTemplateUtil.java" />
</list>
</option>
</component>
<component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
<component name="JsGulpfileManager">
<detection-done>true</detection-done>
<sorting>DEFINITION_ORDER</sorting>
</component>
<component name="MavenImportPreferences">
<option name="importingSettings">
<MavenImportingSettings>
<option name="importAutomatically" value="true" />
</MavenImportingSettings>
</option>
</component>
<component name="MavenProjectNavigator">
<treeState>
<expand />
<select />
</treeState>
</component>
<component name="NodePackageJsonFileManager">
<packageJsonPaths />
</component>
<component name="ProjectFrameBounds" extendedState="6">
<option name="x" value="168" />
<option name="y" value="25" />
<option name="width" value="1693" />
<option name="height" value="1056" />
</component>
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="ProjectPane">
<subPane>
<expand>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="main" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="main" type="462c0819:PsiDirectoryNode" />
<item name="java" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="main" type="462c0819:PsiDirectoryNode" />
<item name="java" type="462c0819:PsiDirectoryNode" />
<item name="utils" type="462c0819:PsiDirectoryNode" />
</path>
<path>
<item name="CommonUtils" type="b2602c69:ProjectViewProjectNode" />
<item name="CommonUtils" type="462c0819:PsiDirectoryNode" />
<item name="src" type="462c0819:PsiDirectoryNode" />
<item name="main" type="462c0819:PsiDirectoryNode" />
<item name="java" type="462c0819:PsiDirectoryNode" />
<item name="utils" type="462c0819:PsiDirectoryNode" />
<item name="config" type="462c0819:PsiDirectoryNode" />
</path>
</expand>
<select />
</subPane>
</pane>
<pane id="Scope" />
<pane id="AndroidView" />
<pane id="PackagesPane" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
<property name="project.structure.last.edited" value="Project" />
<property name="project.structure.proportion" value="0.0" />
<property name="project.structure.side.proportion" value="0.2" />
<property name="settings.editor.selected.configurable" value="MavenSettings" />
</component>
<component name="RecentsManager">
<key name="CopyClassDialog.RECENTS_KEY">
<recent name="site.cnkj.util.domain.redis" />
</key>
<key name="CopyFile.RECENT_KEYS">
<recent name="H:\github\CommonUtils\Java\CommonUtils" />
</key>
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration default="true" type="Application" factoryName="Application">
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
</configuration>
<configuration default="true" type="JUnit" factoryName="JUnit">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="TEST_OBJECT" value="class" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<patterns />
</configuration>
<configuration default="true" type="TestNG" factoryName="TestNG">
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
<option name="ALTERNATIVE_JRE_PATH" />
<option name="SUITE_NAME" />
<option name="PACKAGE_NAME" />
<option name="MAIN_CLASS_NAME" />
<option name="METHOD_NAME" />
<option name="GROUP_NAME" />
<option name="TEST_OBJECT" value="CLASS" />
<option name="VM_PARAMETERS" value="-ea" />
<option name="PARAMETERS" />
<option name="WORKING_DIRECTORY" value="%MODULE_WORKING_DIR%" />
<option name="OUTPUT_DIRECTORY" />
<option name="PASS_PARENT_ENVS" value="true" />
<option name="TEST_SEARCH_SCOPE">
<value defaultName="singleModule" />
</option>
<option name="USE_DEFAULT_REPORTERS" value="false" />
<option name="PROPERTIES_FILE" />
<properties />
<listeners />
</configuration>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="eb22885f-8347-4349-9d11-17e6e18e8973" name="Default" comment="" />
<created>1564120653653</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1564120653653</updated>
<workItem from="1564120658771" duration="3389000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="3389000" />
</component>
<component name="ToolWindowManager">
<frame x="-8" y="-8" width="1936" height="1056" extended-state="6" />
<layout>
<window_info anchor="right" id="Palette" />
<window_info anchor="bottom" id="Event Log" side_tool="true" />
<window_info anchor="right" id="Maven Projects" weight="0.32995737" />
<window_info anchor="bottom" id="Database Changes" show_stripe_button="false" />
<window_info id="Capture Tool" />
<window_info id="Designer" />
<window_info anchor="right" id="Database" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info id="UI Designer" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="right" id="Palette&#9;" />
<window_info id="Image Layers" />
<window_info anchor="right" id="Capture Analysis" />
<window_info anchor="bottom" id="Version Control" show_stripe_button="false" />
<window_info active="true" anchor="bottom" id="Run" order="2" visible="true" weight="0.32897604" />
<window_info anchor="bottom" id="Spring" />
<window_info anchor="bottom" id="Terminal" />
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.25" />
<window_info anchor="right" id="Bean Validation" />
<window_info anchor="bottom" id="SonarLint" />
<window_info anchor="bottom" id="Find" order="1" weight="0.32897604" />
<window_info anchor="right" id="Theme Preview" />
<window_info id="Favorites" side_tool="true" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="VcsContentAnnotationSettings">
<option name="myLimit" value="2678400000" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/util/domain/redis/Receiver.java">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/util/config/RedisConfig.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="460">
<caret line="58" column="75" selection-start-line="58" selection-start-column="75" selection-end-line="58" selection-end-column="75" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/AsyncExecutePool.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="440">
<caret line="22" column="41" lean-forward="true" selection-start-line="22" selection-start-column="41" selection-end-line="22" selection-end-column="41" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/RedisConfig.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="420">
<caret line="21" column="26" lean-forward="true" selection-start-line="21" selection-start-column="26" selection-end-line="21" selection-end-column="26" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/AsyncThreadPoolConfig.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="11" column="36" selection-start-line="11" selection-start-column="36" selection-end-line="11" selection-end-column="36" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/ElasticsearchConfig.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="260">
<caret line="34" column="34" lean-forward="true" selection-start-line="34" selection-start-column="34" selection-end-line="34" selection-end-column="34" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/config/RestTemplateConfig.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-780">
<caret line="3" column="41" lean-forward="true" selection-start-line="3" selection-start-column="41" selection-end-line="3" selection-end-column="41" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/admin/ActuatorInfoEntity.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="12" column="13" selection-start-line="12" selection-start-column="13" selection-end-line="12" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/admin/ReportEntity.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="13" column="13" selection-start-line="13" selection-start-column="13" selection-end-line="13" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/DataResult.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="300">
<caret line="15" column="45" lean-forward="true" selection-start-line="15" selection-start-column="45" selection-end-line="15" selection-end-column="45" />
<folding>
<element signature="imports" expanded="true" />
<element signature="e#232#233#0" expanded="true" />
<element signature="e#264#265#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/MonitorEntity.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="34">
<caret line="12" column="13" selection-start-line="12" selection-start-column="13" selection-end-line="12" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/domain/BaseResult.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="8" column="13" selection-start-line="8" selection-start-column="13" selection-end-line="8" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/AlarmUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="140">
<caret line="8" column="13" selection-start-line="8" selection-start-column="13" selection-end-line="8" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/CommonInfo.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="246">
<caret line="21" column="40" selection-start-line="21" selection-start-column="40" selection-end-line="21" selection-end-column="40" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/LogUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="160">
<caret line="30" column="65" selection-start-line="30" selection-start-column="65" selection-end-line="30" selection-end-column="65" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/DateUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="40">
<caret line="2" column="7" lean-forward="true" selection-start-line="2" selection-start-column="7" selection-end-line="2" selection-end-column="7" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/FileEncryptDecrypt.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="540">
<caret line="27" column="17" selection-start-line="27" selection-start-column="17" selection-end-line="27" selection-end-column="17" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/FileUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state>
<caret line="145" column="5" selection-start-line="145" selection-start-column="5" selection-end-line="145" selection-end-column="5" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/GracefulShutdown.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="380">
<caret line="19" column="24" selection-start-line="19" selection-start-column="24" selection-end-line="19" selection-end-column="24" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/HttpCommonUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="206">
<caret line="116" column="69" lean-forward="true" selection-start-line="116" selection-start-column="69" selection-end-line="116" selection-end-column="69" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/JacksonUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-364">
<caret line="25" column="19" selection-start-line="25" selection-start-column="19" selection-end-line="25" selection-end-column="19" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/LoggerUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="432">
<caret line="220" column="47" lean-forward="true" selection-start-line="220" selection-start-column="47" selection-end-line="220" selection-end-column="47" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/RedisUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-960">
<caret line="24" column="20" lean-forward="true" selection-start-line="24" selection-start-column="20" selection-end-line="24" selection-end-column="20" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/RestTemplateUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-760">
<caret line="18" column="38" lean-forward="true" selection-start-line="18" selection-start-column="38" selection-end-line="18" selection-end-column="38" />
<folding>
<element signature="imports" expanded="true" />
</folding>
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/RSAEncrypt.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="-5314">
<caret line="27" column="13" selection-start-line="27" selection-start-column="13" selection-end-line="27" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/ShutdownHookThread.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="66">
<caret line="10" column="13" selection-start-line="10" selection-start-column="13" selection-end-line="10" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/src/main/java/site/cnkj/utils/StringUtil.java">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="140">
<caret line="14" column="13" selection-start-line="14" selection-start-column="13" selection-end-line="14" selection-end-column="13" />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/pom.xml">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="377">
<caret line="218" column="29" selection-start-line="218" selection-start-column="29" selection-end-line="218" selection-end-column="29" />
</state>
</provider>
</entry>
</component>
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>1.8</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

1
README.md Normal file
View File

@ -0,0 +1 @@
# CommonUtil

209
pom.xml Normal file
View File

@ -0,0 +1,209 @@
<?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>
<groupId>site.cnkj</groupId>
<artifactId>CommonUtil</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<esVersion>5.6.0</esVersion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!--es-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${esVersion}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${esVersion}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client-sniffer</artifactId>
<version>${esVersion}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${esVersion}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client-sniffer</artifactId>
<version>${esVersion}</version>
</dependency>
<!--kafka-->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<!--<version>2.10.3</version>-->
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<licenses>
<license>
<name>GNU General Public License v3.0</name>
<url>http://www.gnu.org/licenses/agpl-3.0.html</url>
<distribution>repo</distribution>
<comments>A socket manager</comments>
</license>
</licenses>
<developers>
<developer>
<name>liuxuewen</name>
<url>https://github.com/carolcoral</url>
<email>lxw@cnkj.site</email>
</developer>
</developers>
<scm>
<connection>scm:git:https://github.com/carolcoral/CommonUtils.git</connection>
<developerConnection>scm:git:https://github.com/carolcoral/CommonUtils.git</developerConnection>
<url>https://github.com/carolcoral</url>
<tag>v${project.version}</tag>
</scm>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<name>Maven Central Staging Repository</name>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project>

View File

@ -0,0 +1,412 @@
package site.cnkj.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/*
* @version 1.0 created by LXW on 2018/11/8 16:11
*/
public class DateUtil {
public static class DATEFORMATE {
//基本单位
public static final String BASETIME_yyyy = "yyyy";
//基本单位
public static final String BASETIME_MM = "MM";
//基本单位
public static final String BASETIME_dd = "dd";
//基本单位
public static final String BASETIME_HH = "HH";
//基本单位
public static final String BASETIME_mm = "mm";
//基本单位
public static final String BASETIME_ss = "ss";
//基本单位 毫秒
public static final String BASETIME_SSS = "SSS";
//--
public static final String FULLTIMEBY_yMd = "yyyy-MM-dd";
//--
public static final String FULLTIMEBY_yMdH = "yyyy-MM-dd HH";
//-- :
public static final String FULLTIMEBY_yMdHm = "yyyy-MM-dd HH:mm";
//-
public static final String FULLTIMEBY_yM = "yyyy-MM";
//-
public static final String FULLTIMEBY_Md = "MM-dd";
//::
public static final String FULLTIMEBY_Hms = "HH:mm:ss";
//:
public static final String FULLTIMEBY_Hm = "HH:mm";
//:
public static final String FULLTIMEBY_ms = "mm:ss";
//::.毫秒
public static final String FULLTIMEBY_HmsS = "HH:mm:ss.SSS";
//年月日 无分割
public static final String NOSEGMENTATION_yMd = "yyyyMMdd";
//时分 无分割
public static final String NOSEGMENTATION_Hm = "HHmm";
//时分秒 无分割
public static final String NOSEGMENTATION_Hms = "HHmmss";
//时分秒毫秒 无分割
public static final String NOSEGMENTATION_HmsS = "HHmmssSSS";
//年月日时分 无分割
public static final String NOSEGMENTATION_yMdHm = "yyyyMMddHHmm";
//年月日时分秒 无分割
public static final String NOSEGMENTATION_yMdHms = "yyyyMMddHHmmss";
//年月日时分秒毫秒 无分割
public static final String NOSEGMENTATION_yMdHmsS = "yyyyMMddHHmmssSSS";
//年月日 点分割
public static final String POINT_yMd = "yyyy.MM.dd";
//时分秒 点分割
public static final String POINT_Hms = "HH.mm.ss";
//-- ::
public static final String FULLTIMEBY_yMdHms = "yyyy-MM-dd HH:mm:ss";
//-- ::.毫秒
public static final String FULLTIMEBY_yMdHmsS = "yyyy-MM-dd HH:mm:ss.SSS";
//格式化 --
public static final String FULLTIMEFORMAT_yMd = "yyyy年MM月dd日";
//格式化 ::
public static final String FULLTIMEFORMAT_Hms = "HH时mm分ss秒";
//格式化 -- ::
public static final String FULLTIMEFORMAT_yMdHms = "yyyy年MM月dd日 HH时mm分ss秒";
//格式化 -- ::.毫秒
public static final String FULLTIMEFORMAT_yMdHmsS = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒";
}
/**
* 日期字符串转日期格式
*
* @param date 日期字符串
* @param timeFormat 转换后的日期格式
* @return
*/
public static Date dateStringToDate(String date, String timeFormat) {
SimpleDateFormat sdf = new SimpleDateFormat(timeFormat);
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String timeStamp2fulltime(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMATE.FULLTIMEBY_yMdHms);
return sdf.format(date);
}
/**
* 获取指定日期的零点时间戳
*
* @param time 时间
* @param timeFormat 时间对应格式
* @return 零点时间戳(0 : 0 : 0)
*/
public static long getTodayEarlyMorning(String time, String timeFormat) {
long current = translateDatetoTimestamp(time, timeFormat);//当前时间毫秒数
long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//前一天的零点零分零秒的毫秒数
long startTime = zero + 24 * 60 * 60 * 1000;
return startTime;
}
/**
* 获取指定日期的晚上24点的时间戳
*
* @param time 时间
* @param timeFormat 时间对应格式
* @return 当天24点的时间戳(23 : 59 : 59)
*/
public static long getTodayLaterMorning(String time, String timeFormat) {
long current = translateDatetoTimestamp(time, timeFormat);//当前时间毫秒数
long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//前一天的零点零分零秒的毫秒数
long endTime = zero + 24 * 60 * 60 * 1000 * 2 - 1;
return endTime;
}
/**
* 获取当前日期的过去指定天数长度的零点时时间戳包含当天
*
* @param maxDays 3 (2018/10/11 0:0:0)
* @return 2018/10/09 0:0:0 的时间戳
*/
public static long getLastDaysTimestamp(int maxDays) {
//当前时间毫秒数
long current = System.currentTimeMillis();
//今天零点零分零秒的毫秒数
long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
long lastThirty = zero - 24 * 60 * 60 * 1000 * (maxDays);
return lastThirty;
}
/**
* 获取过去指定时间的时间戳
*
* @param pastTime 指定的时间数量 5
* @param type 时间的类型 d日 H时 m分 s秒 S毫秒 不写默认单位秒
* @param timeFormat 转换后的时间戳格式化的标准 不写默认格式 -- ::
* @return
*/
public static String getThePastTime(int pastTime, String type, String timeFormat) {
if (type == null) {
type = "s";
}
if (timeFormat == null) {
timeFormat = DATEFORMATE.FULLTIMEBY_yMdHmsS;
}
long date = System.currentTimeMillis();
Long now_time = new Long(1);
if ("S".equals(type)) {
now_time = date - pastTime;
} else if ("s".equals(type)) {
now_time = date - pastTime * 1000;
} else if ("m".equals(type)) {
now_time = date - pastTime * 1000 * 60;
} else if ("H".equals(type)) {
now_time = date - pastTime * 1000 * 60 * 60;
} else if ("d".equals(type)) {
now_time = date - pastTime * 1000 * 60 * 60 * 24;
}
String finalTime = translateTimeToDate(now_time, timeFormat);
return finalTime;
}
public static String getThePastTime(int pastTime) {
return getThePastTime(pastTime, null, null);
}
public static String getThePastTime(int pastTime, String type) {
return getThePastTime(pastTime, type, null);
}
/**
* 获取当前系统时间的时间戳
*
* @return 时间戳
*/
public static Long getCurrentTime() {
return System.currentTimeMillis();
}
/**
* 获取当前时间规整以5分钟为单位的时间
*
* @param currentTime 时间搓
* @param min 多少分钟的倍数如当前时间16:38 以为5为倍数规整后的时间为1635
* @return 时间 201906211635
*/
public static String getCurrentTimePutInOrder(long currentTime, long min) {
try {
long needTime = 0;
//北京时间和零时区差八个小时所以代码中如果大于八个小时取余就有问题
if (min >= 8 * 60) {
return new SimpleDateFormat(DATEFORMATE.NOSEGMENTATION_yMdHm).format(getMinDate(currentTime));
} else {
needTime = currentTime - currentTime % (min * 60L * 1000L);
}
return new SimpleDateFormat(DATEFORMATE.NOSEGMENTATION_yMdHm).format(new Date(needTime));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取当天的日期
*
* @param time 时间搓
* @return
* @throws ParseException
*/
public static Date getMinDate(Long time) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMATE.FULLTIMEBY_yMd);
Date newDate = sdf.parse(sdf.format(time));
return newDate;
}
/**
* 获取指定格式的当前时间
*
* @return 时间
*/
public static String getNowTimeByFormat(String timeFormat) {
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
String today = simpleDateFormat.format(date);
return today;
}
/**
* 转换时间戳位时间格式
*
* @param timestamp 时间戳(long)
* @param timeFormat 转换的时间格式
* @return 时间
*/
public static String translateTimeToDate(Long timestamp, String timeFormat) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
String da = simpleDateFormat.format(timestamp);
return da;
}
/**
* 字符串转成时间格式
*
* @param time 字符串
* @param timeFormat 转换格式
* @return 时间格式
*/
public static Date translateStringToDate(String time, String timeFormat) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
Date da = null;
try {
da = simpleDateFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return da;
}
/**
* 13位时间戳转date格式
*
* @param timestamp 时间戳
* @param timeFormat 时间格式
* @return
*/
public static Date translateTimestampToDate(Long timestamp, String timeFormat) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
String time = translateTimeToDate(timestamp, timeFormat);
Date da = null;
try {
da = simpleDateFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return da;
}
/**
* 时间转时间戳
*
* @param time 需要转换的时间
* @param timeFormat 时间对应的格式
* @return 13位时间戳
*/
public static Long translateDatetoTimestamp(String time, String timeFormat) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
Date date = null;
try {
date = simpleDateFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
if (date == null) {
return null;
}
long res = date.getTime();
return res;
}
/**
* 序列化字符串为时间格式
*
* @param time 需要转换的字符串 (20181011 10:11:12.013)
* @param timeFormat 字符串对应的时间格式 (yyyyMMdd HH:mm:ss.SSS)
* @param timeTranselate 转换后需要的字符串格式 (yyyy年M月dd日 HH时mm分ss秒SSS毫秒)
* @return 2018年10月11日 10时11分12秒13毫秒
*/
public static String serializationDate(String time, String timeFormat, String timeTranselate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
try {
Date date = simpleDateFormat.parse(time);
SimpleDateFormat dateFormat = new SimpleDateFormat(timeTranselate);
String formatTime = dateFormat.format(date);
return formatTime;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取指定天数前的日期集合包含当天
*
* @param num 天数
* @param time 时间
* @param timeFormat 时间格式
* @param timeTranslate 输出格式
* @return 日期集合
*/
public static List<String> getDesignationDay(int num, String time, String timeFormat, String timeTranslate) {
List<String> days = new ArrayList<String>();
Long timestamp_time = translateDatetoTimestamp(time, timeFormat);
for (int i = 0; i < num; i++) {
Long new_time = timestamp_time - i * 24 * 60 * 60 * 1000;
String today = translateTimeToDate(new_time, timeTranslate);
days.add(today);
}
return days;
}
/**
* 时间切割机小时切割
*
* @param cutTime 切割小时数 2小时 = 2
* @param startTime 开始时间戳 10位
* @param endTime 结束时间戳 10位
* @return Map<序号, 时间段> 切割后时间段列表
*/
public static Map<Integer, String> splitTimestamp(int cutTime, long startTime, long endTime) {
List<String> timeList = new ArrayList<>();
Map timeMap = new LinkedHashMap();
startTime = startTime * 1000;
endTime = endTime * 1000;
if (cutTime <= 0) {
timeList.add(String.valueOf(String.valueOf(startTime).concat(",").concat(String.valueOf(endTime))));
} else if (cutTime > 0 && endTime > startTime) {
long cut = ((endTime - startTime) / 3600000 / cutTime) + ((endTime - startTime) / 3600000 % cutTime);
long timeInterval = (endTime - startTime) / cut;
int i = 0;
while (true) {
Object put;
if (startTime < endTime) {
if ((startTime + timeInterval) > endTime) {
timeList.add(String.valueOf(String.valueOf(startTime).concat(",").concat(String.valueOf(endTime))));
put = timeMap.put(i, String.valueOf(String.valueOf(startTime).concat(",").concat(String.valueOf(endTime))));
} else {
timeList.add(String.valueOf(String.valueOf(startTime).concat(",").concat(String.valueOf(startTime + timeInterval))));
put = timeMap.put(i, String.valueOf(String.valueOf(startTime).concat(",").concat(String.valueOf(startTime + timeInterval))));
}
i++;
} else if (startTime >= endTime) {
break;
}
startTime = startTime + timeInterval;
}
}
return timeMap;
}
/**
* 当前时间与周期时间的时间差
* 时间单位
*
* @param executorTime 执行周期
* @return 周期执行的等待时间
*/
public static int executorsDelayTime(int executorTime) {
//获取当前时间与周期时间的差
long nowTime = System.currentTimeMillis();
int timeDiscrepancy = Integer.parseInt(String.valueOf(nowTime % (executorTime * 1000) / 1000));
int delayTime = executorTime - timeDiscrepancy;
return delayTime;
}
}

View File

@ -0,0 +1,110 @@
package site.cnkj.utils;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Security;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/*
* @version 1.0 created by LXW on 2019/4/15 15:31
* @desc 对文件内容RSA加解密
*/
public class FileEncryptDecrypt {
private static final String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
private static final Charset UTF8 = Charset.forName("UTF-8");
static {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
/**
* 加密文件
* @param keyPath 公钥路径DER
* @param input 输入文件地址
* @param output 输出文件地址
*/
public static boolean encrypt(String keyPath, String input, String output){
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
List<String> list = new ArrayList();
try {
byte[] buffer = Files.readAllBytes(Paths.get(keyPath));
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
File inputFile = new File(input);
File outputFile = new File(output);
fileInputStream = new FileInputStream(inputFile);
fileOutputStream = new FileOutputStream(outputFile);
byte[] inputByte = new byte[116];
int len;
while((len = fileInputStream.read(inputByte)) != -1){
list.add(new String(inputByte, 0, len));
}
for (String s : list) {
byte [] encrypted = encrypt(publicKey, s);
fileOutputStream.write(encrypted);
fileOutputStream.flush();
}
fileOutputStream.close();
fileInputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private static byte[] encrypt(PublicKey publicKey, String message) throws Exception {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM,"BC");
cipher.init(Cipher.ENCRYPT_MODE, publicKey, new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.getEncoder().encode(cipher.doFinal(message.getBytes(UTF8)));
}
/**
* 从字符串中加载公钥
*
*/
private static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = new BASE64Decoder().decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
}
}
//public static void main(String [] args) throws Exception {
// encrypt("F:\\dls\\robot-dls-file\\config\\rsa_public_key.der",
// "C:\\Users\\Carol\\Desktop\\file\\868663032830438_migu$user$login$_1554947856915.log",
// "C:\\Users\\Carol\\Desktop\\decrypt\\868663032830438_migu$user$login$_1557208800000.log"
// );
//}
}

View File

@ -0,0 +1,168 @@
package site.cnkj.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
/*
* @version 1.0 created by LXW on 2019/1/31 15:32
*/
public class FileUtil {
/**
* 检查文件大小
* @param filePath 完整文件路径
* @param num mb 的倍数 1024 MB = 1 GB
* @return
*/
public static Boolean checkFileSize(String filePath, int num) {
File file = new File(filePath);
return checkFileSize(file, num);
}
public static Boolean checkFileSize(File file, int num) {
Boolean flag = false;
try {
long size = file.length();
long mb = 1048576;
long res = size/(mb*num);
if (res > 0){
flag = true;
}else if (res <= 0){
flag = false;
}
}catch (Exception e){
e.printStackTrace();
}finally {
return flag;
}
}
/**
* 写入获取的内容到本地指定文件中相同文件追加写入
* @param filePath 文件路径
* @param info 写入内容
*/
public static void writeFile(String filePath, String info){
try {
File file = new File(filePath);
if (!file.exists()){
file.createNewFile();
}
FileUtils.write(file, info.concat("\n"), "utf-8", true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写入日志信息到文件中自动补充写入时间
* @param filePath
* @param info
*/
public static void writeLog(String filePath, String info){
String time = DateUtil.translateTimeToDate(DateUtil.getCurrentTime(), DateUtil.DATEFORMATE.FULLTIMEBY_yMdHmsS);
String fullInfo = time.concat(" ").concat(info);
File file = new File(filePath);
try {
//如果路径不存在则自动创建
if (!file.exists()){
file.createNewFile();
}
FileUtils.write(file, fullInfo.concat("\n"), "utf-8", true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取指定路径文件的总行数
* @param filePath
* @return
*/
public static int getFileAllLineNumbers(String filePath) {
try {
File file = new File(filePath);
return getFileAllLineNumbers(file);
}catch (Exception e){
e.printStackTrace();
}
return -1;
}
public static int getFileAllLineNumbers(File file) {
try {
if (file.isFile()){
FileReader fileReader = new FileReader(file);
LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
lineNumberReader.skip(Long.MAX_VALUE);
int totalLineNumber = lineNumberReader.getLineNumber();
lineNumberReader.close();
fileReader.close();
return totalLineNumber +1;
}
}catch (Exception e){
e.printStackTrace();
}
return -1;
}
/**
* md5加密字符串
* @param content 字符串
* @return 加密后字符串
*/
public static String getMd5Security(String content){
if (content == null || content.length() == 0) {
throw new IllegalArgumentException("String to encript cannot be null or zero length");
}
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(content.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hexString.toString();
}
public static File createFile(String... filePath){
try {
if (filePath.length > 0){
String fullFilePath = StringUtils.join(filePath, File.separator);
File file = new File(fullFilePath);
if (!file.exists()){
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
if (!file.exists()){
file.createNewFile();
}
}
return new File(fullFilePath);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,83 @@
package site.cnkj.utils;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/*
* @version 1.0 created by LXW on 2019/4/25 16:22
* @desc 基于spring的平滑关闭项目
*/
public class GracefulShutdown implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(GracefulShutdown.class);
private volatile Connector connector;
@Override
public void customize(Connector connector) {
this.connector = connector;
}
@Override
public void onApplicationEvent(ContextClosedEvent event) {
try {
// 指定执行的方法
shutdown();
//手动清理内存
System.gc();
LOGGER.warn("清理内存完毕,正在退出服务......");
if (this.connector == null){
return;
}
this.connector.pause();
LOGGER.warn("关闭全部连接......");
Executor executor = this.connector.getProtocolHandler().getExecutor();
if (executor instanceof ThreadPoolExecutor) {
try {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
threadPoolExecutor.shutdown();
LOGGER.warn("当前服务线程池被关闭");
if (!threadPoolExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
LOGGER.warn("Tomcat thread pool did not shut down gracefully within 30 seconds. Proceeding with forceful shutdown");
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
this.connector.stop();
} catch (LifecycleException e) {
e.printStackTrace();
}
}
@Bean
public GracefulShutdown gracefulShutdown() {
return new GracefulShutdown();
}
@Bean
public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(gracefulShutdown);
return factory;
}
/**
* 执行服务关闭前的一些定制化操作
* 通常需要确认以下步骤
* 1.关闭kafka等数据连接
* 2.flush内存中全部的未处理数据
* 3.清理服务中全部待处理的数据
*/
public void shutdown(){}
}

View File

@ -0,0 +1,128 @@
package site.cnkj.utils;
import javax.servlet.http.HttpServletRequest;
import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
/*
* @version 1.0 created by LXW on 2018/10/25 10:04
*/
public class HttpCommonUtil {
public static String hostName = getHostName();
/**
* 获取客户端请求的地址
*
* @param request 客户端请求信息
* @return 客户端地址
*/
public static String getCustomsAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if(ip.equals("127.0.0.1")){
//根据网卡取本机配置的IP
InetAddress inet=null;
try {
inet = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
ip= inet.getHostAddress();
}
}
// 多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
if(ip != null && ip.length() > 15){
if(ip.indexOf(",")>0){
ip = ip.substring(0,ip.indexOf(","));
}
}
return ip;
}
//获取本地ip
public static String getLocalIp(){
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (Exception e) {
e.printStackTrace();
}
String ip=address.getHostAddress().toString();
return ip;
}
//获取本地机器名
public static String getLocalHostName(){
return hostName;
}
private static String getHostName(){
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String hostName=address.getHostName().toString();
return hostName;
}
/**
* 获取当前服务的PID
* @return PID
*/
public static Integer getCurrentPid(){
String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.split("@")[0];
return Integer.valueOf(pid);
}
/**
* 获取当前服务的PID和名字
* @return PID@NAME
*/
public static String getCurrentPidAndName(){
// get name representing the running Java virtual machine.
String name = ManagementFactory.getRuntimeMXBean().getName();
return name;
}
/**
* 获取本地ip地址不含 127 开头的网段
* @return
*/
public static String getHostIp(){
try{
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress ip = (InetAddress) addresses.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& !ip.isLoopbackAddress() //loopback地址即本机地址IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
&& ip.getHostAddress().indexOf(":")==-1){
System.out.println("本机的IP = " + ip.getHostAddress());
return ip.getHostAddress();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,224 @@
package site.cnkj.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
/*
* @version 1.0 created by LXW on 2019/4/1 9:13
*/
public class LoggerUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtil.class);
public static class Level{
public static final String INFO = "INFO";
public static final String WARN = "WARN";
public static final String ERROR = "ERROR";
public static final String DEBUG = "DEBUG";
}
public static class Status{
public static final String SUCCESS = "000000";//成功
public static final String FAILED = "100000";//执行失败
public static final String FAILED_INSERTMD5 = "100001";//插入流水号失败
public static final String FAILED_VERIFYSEPARATOR = "100002";//校验分隔符数量失败
public static final String FAILED_INCLUDDIRTYDATA = "100003";//校验脏数据失败
public static final String ERROR = "200000";//错误
public static final String DEBUG = "300000";//调试开发
public static final String WARN = "400000";//警告
}
public static class Type{
public static final String ERROR_MESSAGE = "error_message";
public static final String SCHEDULE = "schedule";
public static final String BUSINESS = "business";
}
@Data
public static class MonitorEntity {
private String hostName = HttpCommonUtil.getLocalHostName();//机器名
private String timestamp = DateUtil.translateTimeToDate(DateUtil.getCurrentTime(), DateUtil.DATEFORMATE.FULLTIMEBY_yMdHmsS);//时间
private String time = DateUtil.translateTimeToDate(DateUtil.getCurrentTime(), DateUtil.DATEFORMATE.FULLTIMEBY_yMdHmsS);//时间
private String level;//级别
@Nullable private String status;//状态枚举值
@Nullable private String type;//类型
@Nullable private String info;//信息
@Nullable private Object customField;//自定义字段
@Nullable private String stackTrace;//异常信息如果没有则为NULL
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
public static void message(String level, String info, String status, String type, Object customField, Exception stackTrace){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(level);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(type);
monitorEntity.setCustomField(customField);
monitorEntity.setStackTrace(StringUtil.formatException(stackTrace));
if (level.equals(Level.ERROR)){
LOGGER.error(monitorEntity.toString());
}else if (level.equals(Level.INFO)){
LOGGER.info(monitorEntity.toString());
}else if (level.equals(Level.WARN)){
LOGGER.warn(monitorEntity.toString());
}else if (level.equals(Level.DEBUG)){
LOGGER.debug(monitorEntity.toString());
}
}
public static void warn(String info, String type, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(type);
monitorEntity.setCustomField(customField);
LOGGER.warn(monitorEntity.toString());
}
public static void warn(String info, String type){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(type);
LOGGER.warn(monitorEntity.toString());
}
public static void warn(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.WARN);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.WARN);
monitorEntity.setType(Type.BUSINESS);
LOGGER.warn(monitorEntity.toString());
}
public static void error(String info, String status, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setCustomField(customField);
LOGGER.error(monitorEntity.toString());
}
public static void error(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
LOGGER.error(monitorEntity.toString());
}
public static void error(String info, Exception e, String status, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setCustomField(customField);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
}
public static void error(String info, Exception e, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setCustomField(customField);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
}
public static void error(String info, Exception e, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
}
public static void error(String info, Exception e){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.ERROR);
monitorEntity.setType(Type.ERROR_MESSAGE);
monitorEntity.setStackTrace(StringUtil.formatException(e));
LOGGER.error(monitorEntity.toString());
}
public static void error(String info, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.ERROR);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.ERROR_MESSAGE);
LOGGER.error(monitorEntity.toString());
}
public static void info(String info, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.INFO);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setCustomField(customField);
LOGGER.info(monitorEntity.toString());
}
public static void info(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.INFO);
monitorEntity.setInfo(info);
monitorEntity.setStatus(Status.SUCCESS);
monitorEntity.setType(Type.BUSINESS);
LOGGER.info(monitorEntity.toString());
}
public static void debug(String info, String status, Object customField){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.BUSINESS);
monitorEntity.setCustomField(customField);
LOGGER.debug(monitorEntity.toString());
}
public static void debug(String info, String status){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setStatus(status);
monitorEntity.setType(Type.BUSINESS);
LOGGER.debug(monitorEntity.toString());
}
public static void debug(String info){
MonitorEntity monitorEntity = new MonitorEntity();
monitorEntity.setLevel(Level.DEBUG);
monitorEntity.setInfo(info);
monitorEntity.setType(Type.BUSINESS);
LOGGER.debug(monitorEntity.toString());
}
}

View File

@ -0,0 +1,1022 @@
package site.cnkj.utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import java.util.*;
import java.util.concurrent.TimeUnit;
/*
* @version 1.0 created by LXW on 2019/6/26 11:18
*/
public class RedisUtil {
private RedisTemplate<String, Object> redisTemplate;
private String redisName;
public RedisUtil(RedisTemplate<String, Object> redisTemplate, String redisName) {
this.redisTemplate = redisTemplate;
if (StringUtils.isNotEmpty(redisName)){
this.redisName = redisName;
}else {
this.redisName = null;
}
}
/**
* 获取链接的redis的信息等于Command <info>
* @return
*/
public Properties getInfo(){
try {
return redisTemplate.getConnectionFactory().getConnection().info();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 获取链接的redis的信息等于Command <info>
* @param section 指定的属性
* @return
*/
public Properties getInfo(String section){
try {
return redisTemplate.getConnectionFactory().getConnection().info(section);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 指定缓存失效时间
* @param key
* @param time 时间()
* @return
*/
public boolean expire(String key,long time){
try {
if(time>0){
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 不能为null
* @return 时间() 返回0代表为永久有效
*/
public long getExpire(String key){
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key
* @return true 存在 false不存在
*/
public boolean hasKey(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String ... key){
try {
for (String s : key) {
if (StringUtils.isNotEmpty(redisName)){
s = redisName + ":" + s;
}
if(s != null && s.length() > 0){
redisTemplate.delete(s);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 普通缓存获取
* @param key
* @return
*/
public Object get(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForValue().get(key);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 普通缓存放入
* @param key
* @param value
* @return true成功 false失败
*/
public boolean set(String key,Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key
* @param value
* @param time 时间() time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,Object value,long time){
try {
if(time>0){
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 递增
* @param key
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta){
try {
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForValue().increment(key, delta);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
/**
* 递减
* @param key
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
try {
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForValue().increment(key, -delta);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
/**
* HashGet
* @param key 不能为null
* @param item 不能为null
* @return
*/
public Object hget(String key,String item){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().get(key, item);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 获取hashKey对应的所有键值
* @param key
* @return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().entries(key);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* HashSet
* @param key
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, String> map){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* HashSet 并设置时间
* @param key
* @param map 对应多个键值
* @param time 时间()
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForHash().put(key, item, value);
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @param time 时间() 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
hset(key, item, value);
if (time > 0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key 不能为null
* @param item 可以使多个 不能为null
*/
public void hdel(String key, Object... item){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForHash().delete(key,item);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 判断hash表中是否有该项的值
* @param key 不能为null
* @param item 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().hasKey(key, item);
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key
* @param item
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item,double by){
try {
if (by <= 0 ){
throw new RuntimeException("by 增加数值必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().increment(key, item, by);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
/**
* hash递减
* @param key
* @param item
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
try {
if (by <= 0 ){
throw new RuntimeException("by 减少数值必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().increment(key, item, -by);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
/**
* 根据key获取Set中的所有值
* @param key
* @return
*/
public Set<Object> sGet(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key
* @param value
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key
* @param values 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key
* @param time 时间()
* @param values 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
if (time <= 0){
throw new RuntimeException("过期时间必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
Long count = redisTemplate.opsForSet().add(key, values);
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取set缓存的长度
* @param key
* @return
*/
public long sGetSetSize(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 移除值为value的
* @param key
* @param values 可以是多个
* @return 移除的个数
*/
public long sRemove(String key, Object ...values) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForSet().remove(key, values);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获取list缓存的内容
* @param key
* @param start 开始
* @param end 结束 0 -1代表所有值
* @return
*/
public List<Object> lGet(String key,long start, long end){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取list缓存的长度
* @param key
* @return
*/
public long lGetListSize(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 通过索引 获取list中的值
* @param key
* @param index 索引 index>=0时 0 表头1 第二个元素依次类推index<0时-1表尾-2倒数第二个元素依次类推
* @return
*/
public Object lGetIndex(String key, long index){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lRightPush(String key, Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lRightPush(String key, Object value, long time) {
try {
if (time <= 0){
throw new RuntimeException("过期时间必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 将list放入缓存
* @param key
* @param value
* @return
*/
public boolean lRightPushAll(String key, List<Object> value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time 时间()
* @return
*/
public boolean lRightPushAll(String key, List<Object> value, long time) {
try {
if (time <= 0){
throw new RuntimeException("过期时间必须大于0");
}
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForList().rightPushAll(key, value);
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 根据索引修改list中的某条数据
* @param key
* @param index 索引
* @param value
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 删除列表中指定的value
* @param key
* @param count 正数表示从左开始查询删除查询到的第一个负数表示从右开始查询删除查询到的第一个0表示删除符合条件的全部内容
* @param value 指定的值
* @return
*/
public long lRemove(String key, long count, Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 查询某个前缀的全部key
*
* @param key
* @return
*/
public Set<String> getKeys(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.keys(key.concat("*"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取当前redis上的全部key
* @return
*/
public Set<String> getKeys(){
try {
if (StringUtils.isNotEmpty(redisName)){
return redisTemplate.keys(redisName.concat("*"));
}else {
return redisTemplate.keys("*");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取当前redis上的指定hashKey的全部字段
* @param key
* @return
*/
public Set hgetAll(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForHash().keys(key);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 消息发布
* @param channel 通道名
* @param message 信息
*/
public void publish(String channel, String message){
try {
if (StringUtils.isNotEmpty(redisName)){
channel = redisName + ":" + channel;
}
redisTemplate.convertAndSend(channel, message);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从左开始加入全部集合数据
* @param key
* @param value 集合
* @return
*/
public long lLeftPushAll(String key, Collection value){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForList().leftPushAll(key, value);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 从左开始加入一个新元素
* @param key
* @param value 元素
* @return
*/
public long leftPush(String key, String value){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.opsForList().leftPush(key, value);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 从右开始加入一个新元素
* @param key
* @param value 元素
* @return
*/
public long rightPush(String key, Object value) {
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName+":"+key;
}
return redisTemplate.opsForList().rightPush(key, value);
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
/**
* 从左取出第一个元素直到超过设置的时间后仍未取出则自动返回
* @param key
* @param time
* @param timeUnit
* @return
*/
public Object leftPop(String key, long time, TimeUnit timeUnit){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
if (redisTemplate.hasKey(key)){
return redisTemplate.opsForList().leftPop(key, time, timeUnit);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从左取出第一个元素
* @param key
* @return
*/
public Object leftPop(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
if (redisTemplate.hasKey(key)){
return redisTemplate.opsForList().leftPop(key);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从右取出第一个元素
* @param key
* @return
*/
public Object rightPop(String key){
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
if (redisTemplate.hasKey(key)){
return redisTemplate.opsForList().rightPop(key);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从右取出第一个元素并把该元素从左加入到另一个队列中
* @param sourceKey 取出元素的队列
* @param destinationKey 加入元素的队列
* @return
*/
public Object rightPopAndLeftPush(String sourceKey, String destinationKey){
try {
if (StringUtils.isNotEmpty(redisName)){
sourceKey = redisName + ":" + sourceKey;
destinationKey = redisName + ":" + destinationKey;
}
if (redisTemplate.hasKey(sourceKey)){
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从右取出第一个元素并把该元素从左加入到另一个队列中直到超过设置的时间后自动返回
* @param sourceKey 取出元素的队列
* @param destinationKey 加入元素的队列
* @param timeout 时间
* @param unit 时间格式
* @return
*/
public Object rightPopAndLeftPush(String sourceKey, String destinationKey, long timeout, TimeUnit unit){
try {
if (StringUtils.isNotEmpty(redisName)){
sourceKey = redisName + ":" + sourceKey;
destinationKey = redisName + ":" + destinationKey;
}
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Set<String> scan(Long count, String pattern){
Set set = new HashSet();
try {
if (count > 0){
ScanOptions scanOptions = ScanOptions.scanOptions().match(pattern).count(count).build();
Cursor<byte[]> cursor = redisTemplate.getConnectionFactory().getConnection().scan(scanOptions);
while (cursor.hasNext()){
set.add(new String(cursor.next()));
}
return set;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Set<String> scanAll(){
Set set = new HashSet();
try {
ScanOptions scanOptions = ScanOptions.NONE;
Cursor<byte[]> cursor = redisTemplate.getConnectionFactory().getConnection().scan(scanOptions);
while (cursor.hasNext()){
set.add(new String(cursor.next()));
}
return set;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<Map.Entry<Object, Object>> hscan(String key, long count, String pattern){
List<Map.Entry<Object, Object>> list = new ArrayList();
try {
if (count > 0){
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
ScanOptions scanOptions = ScanOptions.scanOptions().match(pattern).count(count).build();
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(key, scanOptions);
while (cursor.hasNext()){
list.add(cursor.next());
}
return list;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<Map.Entry<Object, Object>> hscanAll(String key){
List<Map.Entry<Object, Object>> list = new ArrayList();
try {
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
ScanOptions scanOptions = ScanOptions.NONE;
Cursor<Map.Entry<Object, Object>> cursor = redisTemplate.opsForHash().scan(key, scanOptions);
while (cursor.hasNext()){
list.add(cursor.next());
}
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public long hlen(String key){
if (StringUtils.isNotEmpty(redisName)){
key = redisName + ":" + key;
}
return redisTemplate.getConnectionFactory().getConnection().hLen(key.getBytes());
}
}

View File

@ -0,0 +1,126 @@
package site.cnkj.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
public class RestTemplateUtil {
public static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateUtil.class);
private RestTemplate restTemplate;
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
/**
* post请求json格式对象
* @param object 提交json对象
* @param url 请求地址
* @param cls 设置返回对象
* @param <T> 返回对象
* @return
*/
public <T> T postVieObjectReturn(Object object, String url,Class<T> cls){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> requestEntity = new HttpEntity<Object>(object, headers);
try {
ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, cls);
return responseEntity.getBody();
}catch (Exception e) {
LOGGER.error("postVieObjectReturn",e);
}
return null;
}
/**
* post请求form表单提交
* @param req_payload 表单对象
* @param url 请求地址
* @param cls 设置返回对象
* @param <T> 返回对象
* @return
*/
public <T> T postVieFormReturn(MultiValueMap<String, Object> req_payload,String url,Class<T> cls){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(req_payload, headers);
try {
ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, requestEntity, cls);
return responseEntity.getBody();
}catch (Exception e) {
LOGGER.error("postVieFormReturn请求失败",e);
}
return null;
}
/**
* get 请求带参数
* @param url 请求地址
* @param cls 设置返回对象
* @param req_payload 参数对象
* @param <T> 返回对象
* @return
*/
public <T> T get(String url,Class<T> cls,Map req_payload){
try {
ResponseEntity<T> responseEntity = restTemplate.getForEntity(url,cls,req_payload);
return responseEntity.getBody();
}catch (Exception e) {
LOGGER.error("get请求失败",e);
}
return null;
}
/**
* get请求不带参数
* @param url 请求地址
* @param cls 设置返回对象
* @param <T> 返回对象
* @return
*/
public <T> T get(String url,Class<T> cls){
try {
ResponseEntity<T> responseEntity = restTemplate.getForEntity(url,cls);
return responseEntity.getBody();
}catch (Exception e) {
LOGGER.error("get请求失败",e);
}
return null;
}
/**
* get 请求拼接地址
* @param url 地址
* @param args 参数
* @param cls 对象
* @param <T> 泛型
* @return
*/
public <T> T getWithQ(String url,Class<T> cls, Map<String,Object> args){
try {
String params = new String();
for (String arg : args.keySet()){
params = params + arg + "=" + args.get(arg) + "&";
}
params = params.substring(0, params.length() -1);
url = url + "?" + params;
ResponseEntity<T> responseEntity = restTemplate.getForEntity(url,cls);
return responseEntity.getBody();
}catch (Exception e) {
LOGGER.error("get请求失败",e);
}
return null;
}
}

View File

@ -0,0 +1,69 @@
package site.cnkj.utils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
* @version 1.0 created by LXW on 2019/3/14 13:51
*/
public class StringUtil {
private static final List EscapeStringList = Arrays.asList(".","|","\\","^");
private static final List ESCAPE_TABS = Arrays.asList("\r","\n","\t");
/**
* 自动转义符合条件的字符串
* @param str
* @return
*/
public static String escapeJava(String str) {
int sz;
sz = str.length();
String newStr = new String();
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
if (EscapeStringList.contains(String.valueOf(ch))){
newStr = newStr + "\\"+String.valueOf(ch);
}else {
newStr = newStr + String.valueOf(ch);
}
}
return newStr;
}
/**
* 自动转义特殊制表符
* @param str 字符串
* @return 转义后字符串
*/
public static String escapeString(String str){
for (Object escapeTab : ESCAPE_TABS) {
str = str.replaceAll(
StringEscapeUtils.escapeJava(escapeTab.toString()),
"\\\\\\\\".concat(StringEscapeUtils.escapeJava(escapeTab.toString())));
}
return str;
}
/**
* 格式化Exception为String
* @param e Exception
* @return e.toString
*/
public static String formatException(Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
str = StringEscapeUtils.escapeJava(str);
return str;
}
}

View File

@ -0,0 +1,54 @@
package site.cnkj.utils.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
@Configuration
@ConditionalOnProperty(prefix="spring.async.pool",name = "corePoolSize",matchIfMissing = false)
public class AsyncExecutePool implements AsyncConfigurer {
@Autowired
private AsyncThreadPoolConfig config;
@Bean
public Executor myTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.getCorePoolSize());
executor.setMaxPoolSize(config.getMaxPoolSize());
executor.setQueueCapacity(config.getQueueCapacity());
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
executor.setThreadNamePrefix("MyExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {// 异步任务中异常处理
return new MyAsyncExceptionHandler();
}
class MyAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
log.info("Exception message - " + throwable.getMessage());
log.info("Method name - " + method.getName());
for (Object param : obj) {
log.info("Parameter value - " + param);
}
}
}
}

View File

@ -0,0 +1,52 @@
package site.cnkj.utils.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ConfigurationProperties(prefix = "spring.async.pool")
@ConditionalOnProperty(prefix="spring.async.pool", name = "corePoolSize", matchIfMissing = false)
public class AsyncThreadPoolConfig {
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getKeepAliveSeconds() {
return keepAliveSeconds;
}
public void setKeepAliveSeconds(int keepAliveSeconds) {
this.keepAliveSeconds = keepAliveSeconds;
}
public int getQueueCapacity() {
return queueCapacity;
}
public void setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
}
}

View File

@ -0,0 +1,127 @@
package site.cnkj.utils.config;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.sniff.SniffOnFailureListener;
import org.elasticsearch.client.sniff.Sniffer;
import org.elasticsearch.client.sniff.SnifferBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.Objects;
/*
* @version 1.0 created by LXW on 2018/11/22 9:43
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "common.elasticsearch")
@ConditionalOnProperty(prefix="common.elasticsearch", name = "clusterNodes")
public class ElasticsearchConfig {
private String[] clusterNodes;
private String username;
private String password;
private Integer snifferinterval = 60000;
private Integer maxretrytimeout = 30000; //带超时时间式(毫秒级)
private Integer failuredelay = 3000;
private Integer connectTimeout = 5000;
private Integer socketTimeout = 60000;
private Integer maxRetryTimeoutMillis=60000;
private static final int BUFFER_SIZE = 300 * 1024 * 1024;
private static final int ADDRESS_LENGTH = 2;
private static final String HTTP_SCHEME = "http";
private HttpHost makeHttpHost(String s) {
assert StringUtils.isNotEmpty(s);
String[] address = s.split(":");
if (address.length == ADDRESS_LENGTH) {
String ip = address[0];
int port = Integer.parseInt(address[1]);
return new HttpHost(ip, port, HTTP_SCHEME);
} else {
return null;
}
}
@Bean(name = "RestSniffClient")
public RestClient restEsClient() {
HttpHost[] hosts = Arrays.stream(clusterNodes)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
//自动扫描网段
//监听同网段服务
//Low Level Client init
RestClientBuilder builder = RestClient.builder(hosts).setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
).setRequestConfigCallback((RequestConfig.Builder build) -> {
build.setConnectTimeout(connectTimeout);
build.setSocketTimeout(socketTimeout);
return build;});
builder.setMaxRetryTimeoutMillis(maxRetryTimeoutMillis);
SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
builder.setFailureListener(sniffOnFailureListener);
RestClient lowLevelRestClient = builder.build();
SnifferBuilder snifferBuilder = Sniffer.builder(lowLevelRestClient).setSniffIntervalMillis(snifferinterval);
if (failuredelay > 0) {
snifferBuilder.setSniffAfterFailureDelayMillis(failuredelay);
}
sniffOnFailureListener.setSniffer(snifferBuilder.build());
return lowLevelRestClient;
}
//具备自动扫描功能的客户端
@Bean(name = "HighLevelSniffClient")
public RestHighLevelClient highLevelSniffClient(@Qualifier("RestSniffClient") RestClient restClient) {
return new RestHighLevelClient(restClient);
}
//只扫描指定节点的客户端
@Bean(name = "RestClient")
public RestClient restClient() {
HttpHost[] hosts = Arrays.stream(clusterNodes)
.map(this::makeHttpHost)
.filter(Objects::nonNull)
.toArray(HttpHost[]::new);
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder builder = RestClient.builder(hosts).setHttpClientConfigCallback(
httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
).setRequestConfigCallback((RequestConfig.Builder build) -> {
build.setConnectTimeout(connectTimeout);
build.setSocketTimeout(socketTimeout);
return build;});
builder.setMaxRetryTimeoutMillis(maxRetryTimeoutMillis);
RestClient lowLevelRestClient = builder.build();
return lowLevelRestClient;
}
//只扫描指定节点的客户端
@Bean(name = "HighLevelClient")
public RestHighLevelClient highLevelClient(@Qualifier("RestClient") RestClient restClient) {
return new RestHighLevelClient(restClient);
}
}

View File

@ -0,0 +1,85 @@
package site.cnkj.utils.config;
import site.cnkj.utils.RedisUtil;
import site.cnkj.utils.domain.redis.Receiver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/*
* @version 1.0 created by LXW on 2019/6/25 10:30
*/
@Configuration
public class RedisConfig {
/**
* 指定使用redisUtil包中所有key的前缀如果不需要则默认为空
*/
@Value("${spring.redis.prefixName:''}")
private String redisName = "";
@Bean
public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
//如果不配置Serializer那么存储的时候缺省使用String如果用User类型存储那么会提示错误User can't cast to String
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
// 开启事务
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
@Bean(name = "redisUtil")
public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
RedisUtil redisUtil = new RedisUtil(redisTemplate, redisName);
return redisUtil;
}
@Bean
@ConditionalOnProperty(prefix = "spring.redis.subDescription", name = "channel")
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter, @Value("${spring.redis.subDescription.channel}") String channel) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic(channel));
return container;
}
/**
* 消息监听器适配器绑定消息处理器利用反射技术调用消息处理器的业务方法
* 需要做多少个消息通信就新建多少个bean并且绑定不同的defaultListenerMethod可以使用同一个component
* @param receiver
* @return
*/
@Bean
@ConditionalOnBean(Receiver.class)
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiver");
}
/**redis 读取内容的template */
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}

View File

@ -0,0 +1,80 @@
package site.cnkj.utils.config;
import site.cnkj.utils.RestTemplateUtil;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
@ConditionalOnClass(value = { RestTemplate.class, HttpClient.class })
public class RestTemplateConfig {
@Value("${remote.maxTotalConnect:10}")
private int maxTotalConnect; // 连接池的最大连接数默认为10
@Value("${remote.maxConnectPerRoute:200}")
private int maxConnectPerRoute; // 单个主机的最大连接数
@Value("${remote.connectTimeout:2000}")
private int connectTimeout; // 连接超时默认2s
@Value("${remote.readTimeout:300000}")
private int readTimeout; // 读取超时默认30s
// 创建HTTP客户端工厂
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
// 初始化RestTemplate,并加入spring的Bean工厂由spring统一管理
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
// 重新设置StringHttpMessageConverter字符集为UTF-8解决中文乱码问题
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
@Bean(name = "restTemplateUtil")
public RestTemplateUtil restTemplateUtil(RestTemplate restTemplate) {
RestTemplateUtil restTemplateUtil = new RestTemplateUtil();
restTemplateUtil.setRestTemplate(restTemplate);
return restTemplateUtil;
}
}

View File

@ -0,0 +1,14 @@
package site.cnkj.utils.domain;
import lombok.Data;
/**
* Created by rx on 2018/9/17.
*/
@Data
public class BaseResult {
private String code;
private String desc;
}

View File

@ -0,0 +1,18 @@
package site.cnkj.utils.domain;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
/*
* @version 1.0 created by LXW on 2019/6/10 11:11
*/
@Data
public class DataResult extends BaseResult {
private Object data;
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}

View File

@ -0,0 +1,10 @@
package site.cnkj.utils.domain.redis;
/*
* @version 1.0 created by LXW on 2019/1/9 16:17
*/
public interface Receiver {
Object receiver(String message);
}

View File

@ -0,0 +1,48 @@
package site.cnkj.utils.service;
import lombok.Data;
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@Data
@Component
public class ActuatorInfo implements InfoContributor {
//当前服务名
private String SERVICE_NAME="";
//服务当前进程号
private int SERVICE_PID;
//自定义属性
private Object data = new Object();
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("SERVICE_NAME",SERVICE_NAME);
builder.withDetail("SERVICE_PID", SERVICE_PID);
builder.withDetail("data", data);
}
public void clearAll(){
this.SERVICE_NAME = new String();
this.SERVICE_PID = -1;
this.data = new Object();
}
public Map getAll(){
Map map = new HashMap();
map.put("SERVICE_NAME", getSERVICE_NAME());
map.put("SERVICE_PID", getSERVICE_PID());
map.put("data", getData());
return map;
}
}

View File

@ -0,0 +1,18 @@
package site.cnkj.utils;
import org.junit.Test;
public class CommonApplicationTests {
@Test
public void contextLoads() {
}
public static void main(String[] args){
int rollInterval = 5;
long nowTime = DateUtil.getCurrentTime();
long timeDiscrepancy = nowTime%(rollInterval*60000)/1000;
System.out.println(timeDiscrepancy);
}
}