Common

320 阅读9分钟

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 {

    /**
     * Feign请求头
     * logging:level:....: debug
     *
     * @return
     */
    @Bean
    Logger.Level FeignHttpConfig() {
        return Logger.Level.FULL;
    }


    private final static String feignName = "TestFeign";

    /**
     * 公共请求头
     *
     * @return
     */
    @Bean
    public RequestInterceptor headerInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                /**
                 * 仅限 TestFeign 接口使用
                 */
                String name = requestTemplate.feignTarget().type().getName();

                if (name.contains(feignName)) {
                    // 获取Token
                    String token = "123456";
                    requestTemplate.header("X-Token", token);
                    log.info("公共请求头设置成功 【token:{}】", token);
                }
            }
        };
    }
}

统计系统耗时

// 系统耗时 StopWatch
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";
​
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 245;
​
    /**
     * RSA最大解密密文大小
     */
    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;
    }
    
    /**
     * 私钥分段加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    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);
​
        // URLEncoder编码解决中文乱码问题
        byte[] data = URLEncoder.encode(content, "UTF-8").getBytes("UTF-8");
        // 加密时超过117字节就报错。为此采用分段加密的办法来加密
        byte[] enBytes = null;
        for (int i = 0; i < data.length; i += MAX_ENCRYPT_BLOCK) {
            // 注意要使用2的倍数,否则会出现加密后的内容再解密时为乱码
            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);
    }
    
    /**
     * 公钥分段解密
     *
     * @param content
     * @return
     * @throws Exception
     */
    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;
​
/**
 * @date 2022/08/27
 * @description: 有道翻译
 */
public class InternationUtil {
​
    public static void main(String[] args) throws Exception {
        // 使用API key 时,请求频率限制为每小时1000次,超过限制会被封禁
        // String url = "http://fanyi.youdao.com/openapi.do?keyfrom=dsfesdfesdff&key=1068666577&type=data&doctype=json&version=1.1&q=";
        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!";
        }
    }
​
    /**
     * 将InputStream转换成String
     */
    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;
    }
}

泛型

/**
 * 泛型 方法修改对象属性值
 * @param t
 * @return
 * @param <T>
 * @throws Exception
 */
public static <T> T update(T t) throws Exception{
    // 获取类中指定字段
    // Field message = t.getClass().getDeclaredField("message");
    // 获取类中全部字段
    Field[] declaredFields = t.getClass().getDeclaredFields();
​
    // 循环设置属性值
    for (Field field : declaredFields) {
        // 启用(false 默认)或禁用(true)安全检查
        field.setAccessible(true);
        // 获取属性值
        System.out.println(field.get(t));
        // 修改属性值
        // 注意: 此种方式不能修改成功 String value = message.get(t); value=..... (String final 修饰)
        field.set(t,"what the fuck");
    }
    return t;
}
​
/**
 * @param source
 * @param target
 * @return target在source中出现了多少次
 */
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;
}
​
/**
 * @param source 指定字符串
 * @param target 需要定位的特殊字符或者字符串
 * @param num    第n次出现
 * @return target在source中第n次出现的位置索引
 */
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();
}
​
/**
 * 获取IP
 * @param url
 * @return
 */
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

// 要配合 @EnableAsync,可配置在启动类上,也可配置在ThreadPoolConfig中
// 相同类中的方法调用带@Async的方法是无法异步的,这种情况仍然是同步
/*
​
start
end
start
end
start
end
start
end
test function time is : 2022-10-08 11:10:37
test function time is : 2022-10-08 11:10:38
test function time is : 2022-10-08 11:10:38
test function time is : 2022-10-08 11:10:39
​
*/
​
​
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;
​
/**
 * @date 2022/10/08
 * @description:
 */
@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;
​
/**
 * @date 2022/10/08
 * @description:
 */
@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); // source:[Person(name=111, dog=Person.Dog(eat=111))]
        System.out.println("target:" + logList);    // target:[Person(name=222, dog=Person.Dog(eat=222))]
    }

    /**
     * 深拷贝:前提是对象必须实现Serializable接口,当然如果对象中的一些属性也是对象的话,
     *        属性对象所属的类也必须实现 Serializable接口。  两个内存空间,互不影响
     *          ObjectUtil.cloneByStream(obj)
     *          ObjectUtil.clone(obj)
     * 浅拷贝: BeanUtils.copyProperties(source,target);
     * 基本类型数据: 值传递
     * 对象:地址传递,两个引用指向同一个对象地址,会影响到源地址的值
     * @param personList
     * @return
     */
    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.*;

/**
 * @date 2023/05/20
 * @description:
 */
@RestController
public class FileTest {

    // 默认文件地址
    static final String pngTemp = "/data/paasfss/temp.png";
    static final String jpgTemp = "/data/paasfss/temp.jpg";

    /**
     * 压缩图片
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static MultipartFile compress(MultipartFile multipartFile) throws IOException {
        File file = multipartFileToFile(pngTemp, multipartFile);

        // 只支持jpg格式压缩
        Img.from(file)
                .setQuality(0.6)//压缩比率
                .write(FileUtil.file(jpgTemp));

        return getMultipartFile(new File(jpgTemp));
    }

    /**
     * 将MultipartFile转换为File
     *
     * @param outFilePath 参数
     * @param multiFile   参数
     * @return 执行结果
     */
    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();
        }
    }

    /**
     * File 转 MultipartFile
     *
     * @param file
     * @return
     * @throws IOException
     */
    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;
    }


}