organize the toolkit, add references and reference sources (#835)

* fix : organize the toolkit, add references and reference sources

* fix : add MemoryUtil for get memory info

* fix : code format adjustment
pull/840/head
pizihao 2 years ago committed by GitHub
parent 8e397741d1
commit 8eaf587f6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -19,13 +19,11 @@ package cn.hippo4j.adapter.web;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.common.toolkit.ByteConvertUtil; import cn.hippo4j.common.toolkit.ByteConvertUtil;
import cn.hippo4j.common.toolkit.MemoryUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
/** /**
* Web thread pool run state handler. * Web thread pool run state handler.
*/ */
@ -34,16 +32,13 @@ public class WebThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
@Override @Override
public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) { public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long used = MemoryUtil.heapMemoryUsed();
MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); long max = MemoryUtil.heapMemoryMax();
long used = heapMemoryUsage.getUsed(); String memoryProportion = StringUtil.newBuilder(
long max = heapMemoryUsage.getMax(); "已分配: ",
String memoryProportion = new StringBuilder() ByteConvertUtil.getPrintSize(used),
.append("已分配: ") " / 最大可用: ",
.append(ByteConvertUtil.getPrintSize(used)) ByteConvertUtil.getPrintSize(max));
.append(" / 最大可用: ")
.append(ByteConvertUtil.getPrintSize(max))
.toString();
poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%"); poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%");
poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%"); poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%");
poolRunStateInfo.setMemoryProportion(memoryProportion); poolRunStateInfo.setMemoryProportion(memoryProportion);

@ -22,7 +22,8 @@ import cn.hippo4j.common.function.Matcher;
import java.lang.reflect.Array; import java.lang.reflect.Array;
/** /**
* Array util. * Array util.<br>
* Refer to cn.hutool.core.util.ArrayUtil:<br>
*/ */
public class ArrayUtil { public class ArrayUtil {

@ -22,7 +22,6 @@ import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper; import com.github.dozermapper.core.Mapper;
import lombok.AccessLevel; import lombok.AccessLevel;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;
import java.beans.IntrospectionException; import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
@ -30,7 +29,8 @@ import java.lang.reflect.Method;
import java.util.*; import java.util.*;
/** /**
* Bean util. * Bean util.<br>
* use com.github.dozermapper
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class BeanUtil { public class BeanUtil {
@ -73,6 +73,13 @@ public class BeanUtil {
.orElse(null); .orElse(null);
} }
/**
* map to bean
*
* @param map source data
* @param clazz type
* @param toCamelCase key convert
*/
public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz, boolean toCamelCase) { public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz, boolean toCamelCase) {
if (clazz == null) { if (clazz == null) {
return null; return null;

@ -21,7 +21,8 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* Collection util. * Collection util.<br>
* Refer to cn.hutool.core.collection.CollUtil:<br>
*/ */
public class CollectionUtil { public class CollectionUtil {

@ -46,14 +46,13 @@ public class ContentUtil {
} }
public static String getGroupKey(ThreadPoolParameter parameter) { public static String getGroupKey(ThreadPoolParameter parameter) {
StringBuilder stringBuilder = new StringBuilder(); return StringUtil.createBuilder()
String resultStr = stringBuilder.append(parameter.getTpId()) .append(parameter.getTpId())
.append(Constants.GROUP_KEY_DELIMITER) .append(Constants.GROUP_KEY_DELIMITER)
.append(parameter.getItemId()) .append(parameter.getItemId())
.append(Constants.GROUP_KEY_DELIMITER) .append(Constants.GROUP_KEY_DELIMITER)
.append(parameter.getTenantId()) .append(parameter.getTenantId())
.toString(); .toString();
return resultStr;
} }
public static String getGroupKey(String... parameters) { public static String getGroupKey(String... parameters) {

@ -23,9 +23,7 @@ import lombok.NoArgsConstructor;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Date; import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone; import java.util.TimeZone;
/** /**

@ -23,7 +23,6 @@ import org.springframework.core.io.ClassPathResource;
import java.io.*; import java.io.*;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -52,36 +51,24 @@ public class FileUtil {
return resultReadStr; return resultReadStr;
} }
/**
* According to the line read
*
* @param path the path
* @param charset the charset
*/
public static List<String> readLines(String path, Charset charset) { public static List<String> readLines(String path, Charset charset) {
List<String> strList = new ArrayList<>(); List<String> strList = new ArrayList<>();
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
ClassPathResource classPathResource = new ClassPathResource(path); ClassPathResource classPathResource = new ClassPathResource(path);
try { try (
inputStreamReader = new InputStreamReader(classPathResource.getInputStream(), charset); InputStreamReader in = new InputStreamReader(classPathResource.getInputStream(), charset);
bufferedReader = new BufferedReader(inputStreamReader); BufferedReader reader = new BufferedReader(in)) {
String line; String line;
while ((line = bufferedReader.readLine()) != null) { while ((line = reader.readLine()) != null) {
strList.add(line); strList.add(line);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); throw new IllegalException("file read error", e);
throw new IllegalException("file read error");
} finally {
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
throw new IllegalException("file read error");
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
throw new IllegalException("file read error");
}
}
} }
return strList; return strList;
} }

@ -24,6 +24,7 @@ import static cn.hippo4j.common.constant.Constants.GROUP_KEY_DELIMITER;
/** /**
* Group key. * Group key.
* Refer to com.alibaba.nacos.client.config.common.GroupKey:<br>
*/ */
public class GroupKey { public class GroupKey {

@ -47,10 +47,28 @@ public class IdUtil {
} }
/** /**
* toString * Returns a {@code String} object representing this {@code UUID}.
* *
* @param uuid UUID * <p> The UUID string representation is as described by this BNF:
* @return UUID String * <blockquote><pre>
* {@code
* UUID = <time_low> "-" <time_mid> "-"
* <time_high_and_version> "-"
* <variant_and_sequence> "-"
* <node>
* time_low = 4*<hexOctet>
* time_mid = 2*<hexOctet>
* time_high_and_version = 2*<hexOctet>
* variant_and_sequence = 2*<hexOctet>
* node = 6*<hexOctet>
* hexOctet = <hexDigit><hexDigit>
* hexDigit =
* "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
* | "a" | "b" | "c" | "d" | "e" | "f"
* | "A" | "B" | "C" | "D" | "E" | "F"
* }</pre></blockquote>
*
* @return A string representation of this {@code UUID}
*/ */
public static String toString(UUID uuid, boolean isSimple) { public static String toString(UUID uuid, boolean isSimple) {
long mostSigBits = uuid.getMostSignificantBits(); long mostSigBits = uuid.getMostSignificantBits();

@ -23,7 +23,8 @@ import java.util.Iterator;
import java.util.Objects; import java.util.Objects;
/** /**
* reference google guava * reference google guava<br>
* com.google.common.base.Joiner
*/ */
public class Joiner { public class Joiner {

@ -17,10 +17,7 @@
package cn.hippo4j.common.toolkit; package cn.hippo4j.common.toolkit;
import java.util.Collection; import java.util.*;
import java.util.Dictionary;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Predicate; import java.util.function.Predicate;
@ -151,6 +148,41 @@ public class MapUtil {
return val; return val;
} }
/**
* Fuzzy matching based on Key.
*
* @param sourceMap
* @param filters
* @return
*/
public static List<String> parseMapForFilter(Map<String, ?> sourceMap, String filters) {
List<String> resultList = new ArrayList<>();
if (CollectionUtil.isEmpty(sourceMap)) {
return resultList;
}
sourceMap.forEach((key, val) -> {
if (checkKey(key, filters)) {
resultList.add(key);
}
});
return resultList;
}
/**
* Match the characters you want to query.
*
* @param key
* @param filters
* @return
*/
private static boolean checkKey(String key, String filters) {
if (key.indexOf(filters) > -1) {
return true;
} else {
return false;
}
}
/** /**
* remove value, Thread safety depends on whether the Map is a thread-safe Map. * remove value, Thread safety depends on whether the Map is a thread-safe Map.
* *

@ -28,6 +28,7 @@ import java.util.List;
/** /**
* MD5 util. * MD5 util.
* Refer to com.alibaba.nacos.common.util.Md5Utils:<br>
*/ */
public class Md5Util { public class Md5Util {
@ -96,17 +97,13 @@ public class Md5Util {
sb.append(Constants.WORD_SEPARATOR); sb.append(Constants.WORD_SEPARATOR);
sb.append(dataIdGroupId[1]); sb.append(dataIdGroupId[1]);
// if have tenant, then set it // if have tenant, then set it
if (dataIdGroupId.length == DATA_ID_GROUP_ID_THREE_LEN) { boolean b = (dataIdGroupId.length == DATA_ID_GROUP_ID_THREE_LEN
if (StringUtil.isNotBlank(dataIdGroupId[2])) { || dataIdGroupId.length == DATA_ID_GROUP_ID_FOUR_LEN)
&& StringUtil.isNotBlank(dataIdGroupId[2]);
if (b) {
sb.append(Constants.WORD_SEPARATOR); sb.append(Constants.WORD_SEPARATOR);
sb.append(dataIdGroupId[2]); sb.append(dataIdGroupId[2]);
} }
} else if (dataIdGroupId.length == DATA_ID_GROUP_ID_FOUR_LEN) {
if (StringUtil.isNotBlank(dataIdGroupId[2])) {
sb.append(Constants.WORD_SEPARATOR);
sb.append(dataIdGroupId[2]);
}
}
sb.append(Constants.LINE_SEPARATOR); sb.append(Constants.LINE_SEPARATOR);
} }
// To encode WORD_SEPARATOR and LINE_SEPARATOR invisible characters, encoded value is %02 and %01 // To encode WORD_SEPARATOR and LINE_SEPARATOR invisible characters, encoded value is %02 and %01

@ -0,0 +1,94 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package cn.hippo4j.common.toolkit;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
/**
* memory util<br>
* the obtained information is not invalid, after a long wait, obtain it again
*
* @author liuwenhao
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MemoryUtil {
static MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
static MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
static MemoryUsage noHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
/**
* get used memory in heap
*
* @return long bytes
*/
public static long heapMemoryUsed() {
return heapMemoryUsage.getUsed();
}
/**
* get max memory in heap
*
* @return long bytes
*/
public static long heapMemoryMax() {
return heapMemoryUsage.getMax();
}
/**
* get free memory in heap
*
* @return long bytes
*/
public static long heapMemoryFree() {
return Math.subtractExact(heapMemoryMax(), heapMemoryUsed());
}
/**
* get used memory in no-heap
*
* @return long bytes
*/
public static long noHeapMemoryUsed() {
return noHeapMemoryUsage.getUsed();
}
/**
* get max memory in no-heap
*
* @return long bytes
*/
public static long noHeapMemoryMax() {
return noHeapMemoryUsage.getMax();
}
/**
* get free memory in no-heap
*
* @return long bytes
*/
public static long noHeapMemoryFree() {
return Math.subtractExact(noHeapMemoryMax(), noHeapMemoryUsed());
}
}

@ -29,10 +29,13 @@ import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
/** /**
* Reflect util. * Reflect util.<br>
* Refer to cn.hutool.core.util.ReflectUtil:<br>
* {@link this#getFieldsDirectly(Class, boolean)} <br>
* {@link this#setFieldValue(Object, Field, Object)} <br>
* {@link this#getDefaultValue(Class)} <br>
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ReflectUtil { public class ReflectUtil {

@ -21,7 +21,11 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* String util. * String util.<br>
* Refer to cn.hutool.core.util.StrUtil:<br>
* {@link this#toSymbolCase(CharSequence, char)}<br>
* {@link this#toCamelCase(CharSequence, char)}<br>
* {@link this#subBefore(String, String)}<br>
*/ */
public class StringUtil { public class StringUtil {
@ -53,8 +57,9 @@ public class StringUtil {
/** /**
* Returns {@code true} if the given string is null or is the empty string. * Returns {@code true} if the given string is null or is the empty string.
* * <p>
* this method has been deprecated, use isEmpty() instead. * this method has been deprecated, use isEmpty() instead.
*
* @param str * @param str
* @return * @return
*/ */
@ -302,6 +307,7 @@ public class StringUtil {
* StringUtils.split("abc def", " ") = ["abc", "def"] * StringUtils.split("abc def", " ") = ["abc", "def"]
* StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"] * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
* </pre> * </pre>
*
* @param str the String to parse, may be null * @param str the String to parse, may be null
* @param separatorChars the characters used as the delimiters, * @param separatorChars the characters used as the delimiters,
* @return an array of parsed Strings * @return an array of parsed Strings

@ -15,10 +15,8 @@
* limitations under the License. * limitations under the License.
*/ */
package cn.hippo4j.config.toolkit; package cn.hippo4j.common.toolkit;
import cn.hippo4j.common.toolkit.Assert;
import cn.hippo4j.common.toolkit.CollectionUtil;
import org.junit.Test; import org.junit.Test;
import java.util.HashMap; import java.util.HashMap;
@ -66,9 +64,9 @@ public class MapUtilTest {
@Test @Test
public void computeIfAbsentNotExistKeyTest() { public void computeIfAbsentNotExistKeyTest() {
Map<Object, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("abc", "123"); map.put("abc", "123");
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try { try {
MapUtil.computeIfAbsent(map, null, mappingFunction, "param1", "param2"); MapUtil.computeIfAbsent(map, null, mappingFunction, "param1", "param2");
} catch (Exception e) { } catch (Exception e) {
@ -93,9 +91,9 @@ public class MapUtilTest {
@Test @Test
public void computeIfAbsentNotExistParam1Test() { public void computeIfAbsentNotExistParam1Test() {
Map<Object, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("abc", "123"); map.put("abc", "123");
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try { try {
MapUtil.computeIfAbsent(map, "abc", mappingFunction, null, "param2"); MapUtil.computeIfAbsent(map, "abc", mappingFunction, null, "param2");
} catch (Exception e) { } catch (Exception e) {
@ -107,9 +105,9 @@ public class MapUtilTest {
@Test @Test
public void computeIfAbsentNotExistParam2Test() { public void computeIfAbsentNotExistParam2Test() {
Map<Object, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("abc", "123"); map.put("abc", "123");
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
try { try {
MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", null); MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", null);
} catch (Exception e) { } catch (Exception e) {
@ -121,18 +119,18 @@ public class MapUtilTest {
@Test @Test
public void computeIfAbsentValNotNullTest() { public void computeIfAbsentValNotNullTest() {
Map<Object, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("abc", "123"); map.put("abc", "123");
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
Object ret = MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", "param2"); Object ret = MapUtil.computeIfAbsent(map, "abc", mappingFunction, "param1", "param2");
Assert.isTrue(Objects.equals("123", String.valueOf(ret))); Assert.isTrue(Objects.equals("123", String.valueOf(ret)));
} }
@Test @Test
public void computeIfAbsentValIsNullTest() { public void computeIfAbsentValIsNullTest() {
Map<Object, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("abc", "123"); map.put("abc", "123");
BiFunction<String, String, String> mappingFunction = (a, b) -> a + b; BiFunction<String, String, Object> mappingFunction = (a, b) -> a + b;
Object ret = MapUtil.computeIfAbsent(map, "xyz", mappingFunction, "param1", "param2"); Object ret = MapUtil.computeIfAbsent(map, "xyz", mappingFunction, "param1", "param2");
Assert.isTrue(Objects.equals("param1param2", String.valueOf(ret))); Assert.isTrue(Objects.equals("param1param2", String.valueOf(ret)));
} }

@ -0,0 +1,60 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package cn.hippo4j.common.toolkit;
import org.junit.Assert;
import org.junit.Test;
public class MemoryUtilTest {
@Test
public void heapMemoryUsed() {
long memoryUsed = MemoryUtil.heapMemoryUsed();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void heapMemoryMax() {
long memoryUsed = MemoryUtil.heapMemoryMax();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void heapMemoryFree() {
long memoryUsed = MemoryUtil.heapMemoryFree();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryUsed() {
long memoryUsed = MemoryUtil.noHeapMemoryUsed();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryMax() {
long memoryUsed = MemoryUtil.noHeapMemoryMax();
Assert.assertNotEquals(0, memoryUsed);
}
@Test
public void noHeapMemoryFree() {
long memoryUsed = MemoryUtil.noHeapMemoryFree();
Assert.assertNotEquals(0, memoryUsed);
}
}

@ -72,14 +72,14 @@ public class HttpUtilsTest {
Assert.assertNotNull(data); Assert.assertNotNull(data);
} }
@Test @Test(expected = SocketTimeoutException.class)
public void testRestApiPostTimeout() { public void testRestApiPostTimeout() {
String loginUrl = postUrl + "auth/login"; String loginUrl = postUrl + "auth/login";
LoginInfo loginInfo = new LoginInfo(); LoginInfo loginInfo = new LoginInfo();
loginInfo.setPassword("hippo4j"); loginInfo.setPassword("hippo4j");
loginInfo.setUsername("hippo4j"); loginInfo.setUsername("hippo4j");
loginInfo.setRememberMe(1); loginInfo.setRememberMe(1);
Assert.assertThrows(SocketTimeoutException.class, () -> HttpUtil.post(loginUrl, loginInfo, 1, Result.class)); HttpUtil.post(loginUrl, loginInfo, 1, Result.class);
} }
@Test @Test

@ -21,6 +21,8 @@ import cn.hippo4j.common.model.ManyThreadPoolRunStateInfo;
import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.model.ThreadPoolRunStateInfo;
import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.BeanUtil;
import cn.hippo4j.common.toolkit.ByteConvertUtil; import cn.hippo4j.common.toolkit.ByteConvertUtil;
import cn.hippo4j.common.toolkit.MemoryUtil;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor;
import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper;
import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage;
@ -30,9 +32,6 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.ConfigurableEnvironment;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import static cn.hippo4j.core.toolkit.IdentifyUtil.CLIENT_IDENTIFICATION_VALUE; import static cn.hippo4j.core.toolkit.IdentifyUtil.CLIENT_IDENTIFICATION_VALUE;
@ -50,16 +49,13 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime {
@Override @Override
public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) { public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) {
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); long used = MemoryUtil.heapMemoryUsed();
MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); long max = MemoryUtil.heapMemoryMax();
long used = heapMemoryUsage.getUsed(); String memoryProportion = StringUtil.newBuilder(
long max = heapMemoryUsage.getMax(); "已分配: ",
String memoryProportion = new StringBuilder() ByteConvertUtil.getPrintSize(used),
.append("已分配: ") " / 最大可用: ",
.append(ByteConvertUtil.getPrintSize(used)) ByteConvertUtil.getPrintSize(max));
.append(" / 最大可用: ")
.append(ByteConvertUtil.getPrintSize(max))
.toString();
poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%"); poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%");
poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%"); poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%");
String ipAddress = hippo4JInetUtils.findFirstNonLoopBackHostInfo().getIpAddress(); String ipAddress = hippo4JInetUtils.findFirstNonLoopBackHostInfo().getIpAddress();

@ -17,6 +17,9 @@
package cn.hippo4j.core.proxy; package cn.hippo4j.core.proxy;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
@ -24,6 +27,7 @@ import java.util.concurrent.atomic.AtomicLong;
/** /**
* Rejected proxy util. * Rejected proxy util.
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RejectedProxyUtil { public class RejectedProxyUtil {
/** /**
@ -35,11 +39,10 @@ public class RejectedProxyUtil {
* @return * @return
*/ */
public static RejectedExecutionHandler createProxy(RejectedExecutionHandler rejectedExecutionHandler, String threadPoolId, AtomicLong rejectedNum) { public static RejectedExecutionHandler createProxy(RejectedExecutionHandler rejectedExecutionHandler, String threadPoolId, AtomicLong rejectedNum) {
RejectedExecutionHandler rejectedProxy = (RejectedExecutionHandler) Proxy return (RejectedExecutionHandler) Proxy
.newProxyInstance( .newProxyInstance(
rejectedExecutionHandler.getClass().getClassLoader(), rejectedExecutionHandler.getClass().getClassLoader(),
new Class[]{RejectedExecutionHandler.class}, new Class[]{RejectedExecutionHandler.class},
new RejectedProxyInvocationHandler(rejectedExecutionHandler, threadPoolId, rejectedNum)); new RejectedProxyInvocationHandler(rejectedExecutionHandler, threadPoolId, rejectedNum));
return rejectedProxy;
} }
} }

@ -22,7 +22,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/** /**
* System clock. * System clock.<br>
* Refer to cn.hutool.core.date.SystemClock<br>
*/ */
public class SystemClock { public class SystemClock {

@ -18,6 +18,8 @@
package cn.hippo4j.core.toolkit.inet; package cn.hippo4j.core.toolkit.inet;
import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.config.ApplicationContextHolder;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
@ -39,24 +41,23 @@ import java.util.Optional;
* @author chen.ma * @author chen.ma
* @date 2022/1/5 21:15 * @date 2022/1/5 21:15
*/ */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DynamicThreadPoolAnnotationUtil { public class DynamicThreadPoolAnnotationUtil {
/** /**
* {@param beanName} {@param annotationType} . * {@param beanName} {@param annotationType} .
* *
* @param beanName * @param beanName bean name
* @param annotationType * @param annotationType annotation class
* @param <A> * @param <A> the Annotation type
* @return
*/ */
public static <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) { public static <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType) {
AbstractApplicationContext context = (AbstractApplicationContext) ApplicationContextHolder.getInstance(); AbstractApplicationContext context = (AbstractApplicationContext) ApplicationContextHolder.getInstance();
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
A annotation = Optional.ofNullable(beanFactory) return Optional.of(beanFactory)
.map(each -> (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName)) .map(each -> (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName))
.map(definition -> definition.getResolvedFactoryMethod()) .map(RootBeanDefinition::getResolvedFactoryMethod)
.map(factoryMethod -> AnnotationUtils.getAnnotation(factoryMethod, annotationType)) .map(factoryMethod -> AnnotationUtils.getAnnotation(factoryMethod, annotationType))
.orElse(null); .orElse(null);
return annotation;
} }
} }

@ -35,7 +35,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Inet utils. * Inet utils.<br>
* Refer to org.springframework.cloud.commons.util.InetUtils<br>
*/ */
public class InetUtils implements Closeable { public class InetUtils implements Closeable {
@ -80,7 +81,7 @@ public class InetUtils implements Closeable {
this.log.trace("Testing interface: " + ifc.getDisplayName()); this.log.trace("Testing interface: " + ifc.getDisplayName());
if (ifc.getIndex() < lowest || result == null) { if (ifc.getIndex() < lowest || result == null) {
lowest = ifc.getIndex(); lowest = ifc.getIndex();
} else if (result != null) { } else {
continue; continue;
} }
// @formatter:off // @formatter:off

@ -17,12 +17,12 @@
package cn.hippo4j.config.notify; package cn.hippo4j.config.notify;
import cn.hippo4j.common.toolkit.MapUtil;
import cn.hippo4j.config.event.AbstractEvent; import cn.hippo4j.config.event.AbstractEvent;
import cn.hippo4j.config.event.AbstractSlowEvent;
import cn.hippo4j.config.notify.listener.AbstractSmartSubscriber; import cn.hippo4j.config.notify.listener.AbstractSmartSubscriber;
import cn.hippo4j.config.notify.listener.AbstractSubscriber; import cn.hippo4j.config.notify.listener.AbstractSubscriber;
import cn.hippo4j.config.toolkit.ClassUtil; import cn.hippo4j.config.toolkit.ClassUtil;
import cn.hippo4j.config.toolkit.MapUtil;
import cn.hippo4j.config.event.AbstractSlowEvent;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.Map; import java.util.Map;

@ -22,17 +22,12 @@ import cn.hippo4j.common.constant.Constants;
import cn.hippo4j.common.design.observer.AbstractSubjectCenter; import cn.hippo4j.common.design.observer.AbstractSubjectCenter;
import cn.hippo4j.common.design.observer.Observer; import cn.hippo4j.common.design.observer.Observer;
import cn.hippo4j.common.design.observer.ObserverMessage; import cn.hippo4j.common.design.observer.ObserverMessage;
import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.*;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.Joiner;
import cn.hippo4j.common.toolkit.Md5Util;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.config.event.LocalDataChangeEvent; import cn.hippo4j.config.event.LocalDataChangeEvent;
import cn.hippo4j.config.model.CacheItem; import cn.hippo4j.config.model.CacheItem;
import cn.hippo4j.config.model.ConfigAllInfo; import cn.hippo4j.config.model.ConfigAllInfo;
import cn.hippo4j.config.notify.NotifyCenter; import cn.hippo4j.config.notify.NotifyCenter;
import cn.hippo4j.config.service.biz.ConfigService; import cn.hippo4j.config.service.biz.ConfigService;
import cn.hippo4j.config.toolkit.MapUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;

@ -17,17 +17,13 @@
package cn.hippo4j.config.service; package cn.hippo4j.config.service;
import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.*;
import cn.hippo4j.common.toolkit.JSONUtil;
import cn.hippo4j.common.toolkit.Md5Util;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.base.Results;
import cn.hippo4j.config.event.AbstractEvent; import cn.hippo4j.config.event.AbstractEvent;
import cn.hippo4j.config.event.LocalDataChangeEvent; import cn.hippo4j.config.event.LocalDataChangeEvent;
import cn.hippo4j.config.notify.NotifyCenter; import cn.hippo4j.config.notify.NotifyCenter;
import cn.hippo4j.config.notify.listener.AbstractSubscriber; import cn.hippo4j.config.notify.listener.AbstractSubscriber;
import cn.hippo4j.config.toolkit.ConfigExecutor; import cn.hippo4j.config.toolkit.ConfigExecutor;
import cn.hippo4j.config.toolkit.MapUtil;
import cn.hippo4j.config.toolkit.Md5ConfigUtil; import cn.hippo4j.config.toolkit.Md5ConfigUtil;
import cn.hippo4j.config.toolkit.RequestUtil; import cn.hippo4j.config.toolkit.RequestUtil;
import lombok.SneakyThrows; import lombok.SneakyThrows;

@ -1,82 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package cn.hippo4j.config.toolkit;
import cn.hippo4j.common.toolkit.CollectionUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
/**
* Map util.
*/
public class MapUtil {
public static Object computeIfAbsent(Map target, Object key, BiFunction mappingFunction, Object param1, Object param2) {
Objects.requireNonNull(target, "target");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(mappingFunction, "mappingFunction");
Objects.requireNonNull(param1, "param1");
Objects.requireNonNull(param2, "param2");
Object val = target.get(key);
if (val == null) {
Object ret = mappingFunction.apply(param1, param2);
target.put(key, ret);
return ret;
}
return val;
}
/**
* Fuzzy matching based on Key.
*
* @param sourceMap
* @param filters
* @return
*/
public static List<String> parseMapForFilter(Map<String, ?> sourceMap, String filters) {
List<String> resultList = new ArrayList<>();
if (CollectionUtil.isEmpty(sourceMap)) {
return resultList;
}
sourceMap.forEach((key, val) -> {
if (checkKey(key, filters)) {
resultList.add(key);
}
});
return resultList;
}
/**
* Match the characters you want to query.
*
* @param key
* @param filters
* @return
*/
private static boolean checkKey(String key, String filters) {
if (key.indexOf(filters) > -1) {
return true;
} else {
return false;
}
}
}

@ -36,11 +36,7 @@ import java.util.concurrent.ExecutorService;
* Abstract core thread-pool dynamic refresh. * Abstract core thread-pool dynamic refresh.
*/ */
@Slf4j @Slf4j
public abstract class AbstractConfigThreadPoolDynamicRefresh public abstract class AbstractConfigThreadPoolDynamicRefresh implements ThreadPoolDynamicRefresh, ThreadPoolInitRefresh, InitializingBean {
implements
ThreadPoolDynamicRefresh,
ThreadPoolInitRefresh,
InitializingBean {
private final BootstrapConfigPropertiesBinderAdapt bootstrapConfigPropertiesBinderAdapt; private final BootstrapConfigPropertiesBinderAdapt bootstrapConfigPropertiesBinderAdapt;

Loading…
Cancel
Save