Common
OpenFeign 实现动态url
blog.csdn.net/weixin_4385…
@FeignClient(name = "test",url="http://localhost:9110",configuration = FeignHttpConfig.class)
package com.example.demo05;
import feign.Feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
@Slf4j
public class FeignHttpConfig {
@Bean
Logger.Level FeignHttpConfig() {
return Logger.Level.FULL;
}
private final static String feignName = "TestFeign";
@Bean
public RequestInterceptor headerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
String name = requestTemplate.feignTarget().type().getName();
if (name.contains(feignName)) {
String token = "123456";
requestTemplate.header("X-Token", token);
log.info("公共请求头设置成功 【token:{}】", token);
}
}
};
}
}
统计系统耗时
public class Test {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch("main");
stopWatch.start("task 1 ");
Thread.sleep(500);
stopWatch.stop();
stopWatch.start("task 2 ");
Thread.sleep(500);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint(TimeUnit.MILLISECONDS));
}
}
result:
StopWatch 'main': running time = 1004 ms
---------------------------------------------
ms % Task name
---------------------------------------------
000000503 50% task 1
000000500 50% task 2
RSA 加解密
package com.jovision.mix.common.core.util;
import com.jovision.mix.common.core.enumconst.RsaKeyTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
@Slf4j
@Component
public class RSAUtil {
private static final Logger logger = LoggerFactory.getLogger(RSAUtil.class);
public static final String KEY_ALGORITHM = "RSA";
private static final int MAX_ENCRYPT_BLOCK = 245;
private static final int MAX_DECRYPT_BLOCK = 256;
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes = Base64.decodeBase64(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes = Base64.decodeBase64(key);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
public static String getKeyStr(String keyType) {
ClassPathResource resource = new ClassPathResource("key/" + keyType + ".key");
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
String tempStr = null;
br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
while ((tempStr = br.readLine()) != null) {
if (tempStr != null && !tempStr.startsWith("-")) {
sb.append(tempStr);
}
}
br.close();
} catch (Exception e) {
logger.error("RSAUtil getKeyStr e=" + e.getMessage(), e);
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
}
}
}
String keyStr = sb.toString();
return keyStr;
}
public static String encryptByPrivateKey(String content) throws Exception {
PrivateKey privateKey = getPrivateKey(getConfigKeyStr(RsaKeyTypeEnum.PRIV_KEY.getValue()));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] cipherText = cipher.doFinal(content.getBytes());
String cipherStr = new BASE64Encoder().encode(cipherText);
return cipherStr;
}
public static String encryptLongByPrivateKey(String content) throws Exception {
PrivateKey privateKey = getPrivateKey(getConfigKeyStr(RsaKeyTypeEnum.PRIV_KEY.getValue()));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] data = URLEncoder.encode(content, "UTF-8").getBytes("UTF-8");
byte[] enBytes = null;
for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
byte[] doFinal = cipher.doFinal(ArrayUtils.subarray(data, i, i + MAX_ENCRYPT_BLOCK));
enBytes = ArrayUtils.addAll(enBytes, doFinal);
}
String cipherStr = new BASE64Encoder().encode(enBytes);
return cipherStr;
}
public static String decryptByPublicKey(String content) throws Exception {
PublicKey publicKey = getPublicKey(getConfigKeyStr(RsaKeyTypeEnum.PUB_KEY.getValue()));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] cipherText = new BASE64Decoder().decodeBuffer(content);
byte[] decryptText = cipher.doFinal(cipherText);
return new String(decryptText);
}
public static String decryptLongByPublicKey(String content) {
String str = "";
try {
byte[] pubByte = new BASE64Decoder().decodeBuffer(getConfigKeyStr(RsaKeyTypeEnum.PUB_KEY.getValue()));
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubByte);
KeyFactory fac = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey rsaPubKey = fac.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, rsaPubKey);
byte[] dataBytes = Base64.decodeBase64(content);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = 0;
byte[] cache;
int i = 0;
while (inputLen - offset > 0) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, 0, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
str = new String(decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws Exception {
String content = "12345678654";
String encrypt = encryptByPrivateKey(content);
System.out.println("原文:"+content);
System.out.println("密文:"+encrypt);
String decrypt = decryptByPublicKey(encrypt);
System.out.println("解密:"+decrypt);
String content = "{"mapService": false, "openService": false, "parkService": {"check": false, "count": 10}, "analyService": false, "basicService": false, "cloudService": {"check": false, "count": 10}, "eventService": false, "guardService": {"check": false, "count": 10}, "mediaForward": {"stream": "1MB", "wayNum": 300, "bandWidth": "300MB"}, "centerStorage": {"time": 3, "check": false, "stream": "1MB", "wayNum": 300, "storage": "50TB"}, "upwardService": {"check": false, "upwardPlatformNum": 100, "upwardPlatformCount": 100}, "cockpitService": false, "deviceImportNum": 100, "keyboardService": false, "environmentService": {"check": false, "count": 10}}";
String compress = GzipUtil.compress(content);
System.out.println(compress);
String encrypt = encryptLongByPrivateKey(compress);
System.out.println("密文:" + encrypt);
String decrypt = decryptLongByPublicKey(encrypt);
System.out.println("解密:" + decrypt);
String uncompress = GzipUtil.uncompress(URLDecoder.decode(decrypt,"UTF-8"));
System.out.println(uncompress);
}
}
有道翻译API
package com.example.demo.translate;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
public class InternationUtil {
public static void main(String[] args) throws Exception {
String url = "http://fanyi.youdao.com/openapi.do?keyfrom=xxxxxxx&key=1618693256&type=data&doctype=json&version=1.1&q=";
// 传入要转换的枚举类
changeEnByZh(PaasBusinessErrorEnum.class,url);
}
/**
* 根据中文替换英文翻译
*/
public static <T> void changeEnByZh(Class<T> t,String url) {
URL resource = t.getResource("");
String path = resource.getPath().replace("target/classes", "src/main/java") + t.getSimpleName() + ".java";
System.out.println("update file is : " + path);
List<String> list = FileUtil.readUtf8Lines(path);
String newLine = "\r\n";
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
if (i == 0) {
// 第一行写入
FileUtil.writeUtf8String(value + newLine, path);
} else {
// 之后追加
if (value.contains("),")) {
String[] split = value.substring(value.indexOf("(") + 1, value.indexOf(")")).split(""");
String msgEn = """ + split[1] + """;
String msgZh = split[3];
try {
value = value.replace(msgEn, translate(msgZh,url));
} catch (Exception e) {
System.out.println("使用API key 时,请求频率限制为每小时1000次,超过限制会被封禁");
throw new RuntimeException();
}
System.out.println("change result is : " + value);
}
FileUtil.appendUtf8String(value + newLine, path);
}
}
}
public static String translate(String text,String url) throws Exception {
final String Youdao_Url = url;
StringBuilder YoudaoAPIURL = new StringBuilder();
YoudaoAPIURL.append(Youdao_Url).append(URLEncoder.encode(text, "UTF-8"));
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(YoudaoAPIURL.toString()).openConnection();
String rawData = stream2string(httpURLConnection.getInputStream());
JSONObject jsonObj = null;
try {
jsonObj = JSONUtil.parseObj(rawData);
} catch (Exception e) {
System.out.println(rawData);
throw new RuntimeException();
}
if ("0".equals(jsonObj.get("errorCode").toString())) {
String finalData = jsonObj.get("translation").toString().replace("[", "").replace("]", "");
return finalData;
} else {
return "Error!";
}
}
private static String stream2string(InputStream is) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringWriter writer = new StringWriter();
char[] buffer = new char[10240];
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
reader.close();
return writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Redis 压缩
public class GzipUtils {
/**
* 使用gzip压缩字符串
*
* @param originString 要压缩的字符串
* @return 压缩后的字符串
*/
public static String compress(String originString) {
if (originString == null || originString.length() == 0) {
return originString
}
ByteArrayOutputStream out = new ByteArrayOutputStream()
try (
GZIPOutputStream gzip = new GZIPOutputStream(out)
) {
gzip.write(originString.getBytes())
} catch (Exception e) {
e.printStackTrace()
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray())
}
/**
* 使用gzip解压缩
*
* @param compressedString 压缩字符串
* @return
*/
public static String uncompress(String compressedString) {
if (compressedString == null || compressedString.length() == 0) {
return null
}
ByteArrayOutputStream out = new ByteArrayOutputStream()
byte[] compressedByte = new byte[0]
try {
compressedByte = new sun.misc.BASE64Decoder().decodeBuffer(compressedString)
} catch (Exception e) {
e.printStackTrace()
}
String originString = null
try (
ByteArrayInputStream in = new ByteArrayInputStream(compressedByte)
GZIPInputStream ginzip = new GZIPInputStream(in)
) {
byte[] buffer = new byte[1024]
int offset = -1
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset)
}
originString = out.toString()
} catch (IOException e) {
e.printStackTrace()
}
return originString
}
}
泛型
public static <T> T update(T t) throws Exception{
Field[] declaredFields = t.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
System.out.println(field.get(t));
field.set(t,"what the fuck");
}
return t;
}
private static int countAlarm(String source, String target) {
int index = 0;
int count = 0;
while ((index = source.indexOf(target)) != -1) {
count++;
source = source.substring(index + 1);
}
return count;
}
public static int getIndexOf(String source, String target, int num) {
Pattern pattern = Pattern.compile(target);
Matcher findMatcher = pattern.matcher(source);
int indexNum = 0;
while (findMatcher.find()) {
indexNum++;
if (indexNum == num) {
break;
}
}
return findMatcher.start();
}
public static String getIpByUrl(String url) {
String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(url);
while (matcher.find()) {
return matcher.group();
}
return null;
}
Async
package com.example.demo.async;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Demo {
@Autowired
AsyncDemo asyncDemo;
@GetMapping("/async")
public void test() throws InterruptedException {
System.out.println("start");
asyncDemo.asyncTest();
System.out.println("end");
}
}
package com.example.demo.async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class AsyncDemo {
@Async
public void asyncTest() throws InterruptedException {
Thread.sleep(5000L);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("test function time is : " + dateFormat.format(new Date()));
}
}
package com.example.demo.async;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@EnableAsync
@Configuration
public class ThreadPoolConfig {
@Value("${threadPool.corePoolSize:4}")
private Integer corePoolSize;
@Value("${threadPool.maxPoolSize:8}")
private Integer maxPoolSize;
@Value("${threadPool.queueCapacity:400}")
private Integer queueCapacity;
@Value("${threadPool.keepAliveSeconds:30}")
private Integer keepAliveSeconds;
@Bean("TaskExecutor")
public ThreadPoolTaskExecutor TaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix("middleTaskExecutor-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
工具类使用@Value
注:
1. 要添加@Component注解
2. 其他类不用@Autowired 注入工具类,就可以直接使用lang,因为set/get方法
@Slf4j
@Component
public class CurrentUserUtil {
private static String lang;
public static String getLang(){
return lang;
}
@Value("${system.language}")
public void setLang(String lang){
this.lang = lang;
}
}
对象拷贝
public class Test {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(new Person("111", new Person.Dog("111")));
List<Person> logList = get(personList);
System.out.println("source:" + personList);
System.out.println("target:" + logList);
}
public static List<Person> get(List<Person> personList) {
List<Person> logList = new ArrayList<>();
personList.forEach(person -> {
Person clone = ObjectUtil.clone(person);
if (true) {
clone.setName("222");
Person.Dog dog = clone.getDog();
dog.setEat("222");
}
logList.add(clone);
});
return logList;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable {
private String name;
private Dog dog;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Dog implements Serializable{
private String eat;
}
}
图片转base64
public static void main(String[] args) {
String str = "http://172.16.32.120:9000/underlay/0days/df72938c-ea86-4891-be1d-4b806ff6cd4a"
str = "public/underlay/20231206/aae3edd3-7694-4267-9a68-4a331d8c5aec.jpeg"
String s = imageChangeBase64(str)
System.out.println(s)
}
/**
* 图片转base64
*
* @param imagePath
* @return
*/
public static String imageChangeBase64(String imagePath) {
if (StringUtils.isNotBlank(imagePath)) {
// minio方式直接用,p层方式补全url
if (imagePath.contains("public")) {
imagePath = "http://192.168.114.188:9090/download/" + imagePath
}
System.out.println(imagePath)
ByteArrayOutputStream outPut = new ByteArrayOutputStream()
byte[] data = new byte[1024]
try {
// 创建URL
URL url = new URL(imagePath)
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
conn.setRequestMethod("GET")
conn.setConnectTimeout(10 * 1000)
if (conn.getResponseCode() != 200) {
return "fail"
}
InputStream inStream = conn.getInputStream()
int len = -1
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len)
}
inStream.close()
} catch (IOException e) {
e.printStackTrace()
}
// 对字节数组Base64编码
byte[] encode = Base64.getEncoder().encode(outPut.toByteArray())
return new String(encode)
}
return ""
}
日志打印过滤字段(不会影响数据源)
blog.csdn.net/m0_37899908…
图片压缩
package com.example.demo06;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@RestController
public class FileTest {
static final String pngTemp = "/data/paasfss/temp.png";
static final String jpgTemp = "/data/paasfss/temp.jpg";
public static MultipartFile compress(MultipartFile multipartFile) throws IOException {
File file = multipartFileToFile(pngTemp, multipartFile);
Img.from(file)
.setQuality(0.6)
.write(FileUtil.file(jpgTemp));
return getMultipartFile(new File(jpgTemp));
}
public static File multipartFileToFile(String outFilePath, MultipartFile multiFile) {
if (null == multiFile) {
return null;
}
String fileName = multiFile.getOriginalFilename();
if (null == fileName) {
return null;
}
try {
File toFile;
InputStream ins;
ins = multiFile.getInputStream();
toFile = new File(outFilePath);
inputStreamToFile(ins, toFile);
return toFile;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void inputStreamToFile(InputStream ins, File file) {
try (OutputStream os = new FileOutputStream(file)) {
int bytesRead;
int bytes = 8192;
byte[] buffer = new byte[bytes];
while ((bytesRead = ins.read(buffer, 0, bytes)) != -1) {
os.write(buffer, 0, bytesRead);
}
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static MultipartFile getMultipartFile(File file) throws IOException {
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
return multipartFile;
}
}