123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980 |
- package com.backendsys.modules;
- import cn.hutool.core.util.IdUtil;
- import cn.hutool.json.JSONArray;
- import cn.hutool.json.JSONObject;
- import cn.hutool.json.JSONUtil;
- import com.backendsys.aspect.RateLimiting;
- import com.backendsys.aspect.QueuingPoll;
- import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
- import com.backendsys.modules.common.config.security.utils.JwtUtil;
- import com.backendsys.modules.common.utils.Result;
- import com.backendsys.modules.sdk.baidu.yunapp.entity.ExecuteScriptParams;
- import com.backendsys.modules.sdk.baidu.yunapp.service.YunappService;
- import com.backendsys.modules.sdk.volcengine.entity.VisualFaceSwapV2;
- import com.backendsys.modules.sdk.volcengine.service.VolcengineService;
- import com.backendsys.modules.system.entity.SysUser;
- import com.backendsys.service.TestService;
- import com.backendsys.utils.ResourceUtil;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import cn.afterturn.easypoi.word.WordExportUtil;
- import com.backendsys.utils.MD5Util;
- import com.rabbitmq.client.Channel;
- import com.rabbitmq.client.GetResponse;
- import com.tencentcloudapi.common.Credential;
- //import io.github.pigmesh.ai.deepseek.core.DeepSeekClientImpl;
- //import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException;
- //import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
- import com.volcengine.service.visual.IVisualService;
- import com.volcengine.service.visual.impl.VisualServiceImpl;
- import io.jsonwebtoken.Claims;
- import jakarta.annotation.PostConstruct;
- import jakarta.servlet.ServletContext;
- import org.apache.poi.xwpf.usermodel.XWPFDocument;
- import org.redisson.api.*;
- import org.springframework.amqp.core.*;
- import org.springframework.amqp.core.Queue;
- import org.springframework.amqp.rabbit.annotation.RabbitListener;
- import org.springframework.amqp.rabbit.connection.Connection;
- import org.springframework.amqp.rabbit.core.RabbitAdmin;
- import org.springframework.amqp.rabbit.core.RabbitTemplate;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.web.bind.annotation.*;
- import java.awt.*;
- import java.io.*;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.security.NoSuchAlgorithmException;
- import java.util.*;
- import java.util.List;
- import java.util.concurrent.CompletableFuture;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.TimeUnit;
- import com.tencentcloudapi.common.CommonClient;
- import com.tencentcloudapi.common.exception.TencentCloudSDKException;
- @RestController
- @RequestMapping("/api/test")
- @SuppressWarnings({"rawtypes", "unchecked"})
- public class TestController {
- @Autowired
- private JwtUtil jwtUtil;
- @GetMapping("/testExtractToken")
- public Claims extractToken(String token) {
- Claims claims = jwtUtil.extractAllClaims(token);
- return claims;
- }
- @Value("${tencent.facefusion.secret-id}")
- private String SECRET_ID;
- @Value("${tencent.facefusion.secret-key}")
- private String SECRET_KEY;
- // @Autowired
- // private AmqpAdmin amqpAdmin;
- @Autowired
- private RabbitTemplate rabbitTemplate;
- // private void initRabbitMQ() {
- // System.out.println("-- initRabbitMQ. --");
- //
- // // 交换机
- // amqpAdmin.declareExchange(new DirectExchange("demo.exchange", true, false));
- //
- // // 队列 (TTL + 死信)
- // Map<String, Object> args = new HashMap<>();
- // args.put("x-message-ttl", 5000); // 消息 TTL:60 秒(单位毫秒)
- // amqpAdmin.declareQueue(new Queue("demo.queue", true, false, false, args));
- //
- //// // 队列
- //// amqpAdmin.declareQueue(new Queue("demo.queue", true));
- //
- // // 把队列 demo.queue 绑定到交换机 demo.exchange,路由键设置为 order.create
- // amqpAdmin.declareBinding(
- // BindingBuilder.bind(new Queue("demo.queue"))
- // .to(new DirectExchange("demo.exchange"))
- // .with("order.create")
- // );
- // // 单队列 (无死信)
- // amqpAdmin.declareQueue(new Queue("demo.queue", true));
- // }
- @GetMapping("/testRabbitMQ/send")
- public String send() {
- // initRabbitMQ();
- // rabbitTemplate.convertAndSend("demo.exchange", "order.create", "Hello RabbitMQ!");
- // rabbitTemplate.convertAndSend("", "demo.queue", "Hello RabbitMQ!");
- SysUser sysUser = new SysUser();
- sysUser.setUsername(UUID.randomUUID().toString());
- System.out.println("[Demo][RabbitMQ-发送]:" + sysUser);
- // rabbitTemplate.convertAndSend("", "demo.queue", sysUser);
- rabbitTemplate.convertAndSend("demo.exchange", "demo.create", sysUser);
- return "ok";
- }
- @GetMapping("/testRabbitMQ/poll")
- public String poll() throws Exception {
- // 1. 拿到连接和 channel(不要每次 new)
- Connection connection = rabbitTemplate.getConnectionFactory().createConnection();
- Channel channel = connection.createChannel(false);
- // 2. 手动拉消息,第二个参数传 false 表示“不要自动 ack”
- // GetResponse resp = channel.basicGet("demo.queue", false);
- GetResponse resp = channel.basicGet("demo.queue", false);
- if (resp == null) {
- channel.close();
- connection.close();
- return "no message";
- }
- String body = new String(resp.getBody(), StandardCharsets.UTF_8);
- System.out.println("[Demo][RabbitMQ-手动处理]:" + body);
- // 3. 用同一个 channel 去 ack
- channel.basicAck(resp.getEnvelope().getDeliveryTag(), false);
- channel.close();
- connection.close();
- return "acked: " + body;
- // try {
- // channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
- // } finally {
- // channel.close();
- // }
- // return "acked: " + body;
- }
- // @Autowired
- // private DeepSeekClientImpl deepSeekClient;
- //
- // // https://javaai.pig4cloud.com/deepseek/quickstart
- // // sse 流式返回
- // @GetMapping(value = "/deepseek/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
- // public Flux<ChatCompletionResponse> chat(String prompt) {
- // try {
- // Flux<ChatCompletionResponse> flux = deepSeekClient.chatFluxCompletion(prompt);
- // return flux;
- // } catch (OpenAiHttpException e) {
- // throw new CustException(e.getMessage());
- // }
- // }
- // // 进阶配置(多轮对话)
- // @GetMapping(value = "/chat/advanced", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
- // public Flux<ChatCompletionResponse> advancedChat(String prompt) {
- // ChatCompletionRequest request = ChatCompletionRequest.builder()
- // .model(ChatCompletionModel.DEEPSEEK_REASONER) // 指定推理模型
- // .addUserMessage(prompt) // 用户当前问题
- // .addAssistantMessage("上轮对话结果") // 历史助手回复
- // .addSystemMessage("你是一名AI助理") // 系统角色设定
- // .maxTokens(1000) // 最大生成 token 数
- // .temperature(0.7) // 生成多样性控制
- // .tools(yourFunctionTools) // Function Calling 工具
- // .responseFormat(ChatResponseFormat.JSON) // 结构化响应
- // .build();
- //
- // return deepSeekClient.chatFluxCompletion(request);
- // }
- @Autowired
- private ServletContext servletContext;
- @GetMapping("/tomcat-version")
- public String getTomcatVersion() {
- String serverInfo = servletContext.getServerInfo();
- return "当前Tomcat版本: " + serverInfo;
- }
- /*
- // SubmitMediaModeration 提交审核任务
- // DescribeMediaModeration 查询审核结果
- // SubmitLongVideoFaceFusionJobPro 视频人脸融合异步处理任务,成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
- // QueryVideoFaceFusionJob 通过Job Id查询视频人脸融合任务的进度和状态
- */
- /**
- * [腾讯云-人脸融合] 提交审核任务 (视频)
- */
- @PostMapping("SubmitMediaModeration")
- public String SubmitMediaModeration(@RequestBody Map<String, Object> requestBody) throws TencentCloudSDKException {
- String videoUrl = (String) requestBody.get("videoUrl");
- // String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";
- Credential cred = new Credential(SECRET_ID, SECRET_KEY);
- CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
- String param = "{\"VideoUrl\":\"" + videoUrl + "\"}";
- String resp = client.call("SubmitMediaModeration", param);
- System.out.println(resp);
- return resp;
- }
- /**
- * [腾讯云-人脸融合] 查询审核结果
- */
- @GetMapping("DescribeMediaModeration")
- public String DescribeMediaModeration(String JobId) throws TencentCloudSDKException {
- Credential cred = new Credential(SECRET_ID, SECRET_KEY);
- CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
- String param = "{\"JobId\":\"" + JobId + "\"}";
- String resp = client.call("DescribeMediaModeration", param);
- System.out.println(resp);
- return resp;
- }
- /**
- * 视频人脸融合异步处理任务,成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
- */
- @PostMapping("/SubmitLongVideoFaceFusionJobPro")
- public String SubmitLongVideoFaceFusionJobPro(@RequestBody Map<String, Object> requestBody) {
- try {
- // 从Map中获取参数
- List<Map<String, Object>> TemplateInfos = (List<Map<String, Object>>) requestBody.get("TemplateInfos");
- List<Map<String, Object>> MergeInfos = (List<Map<String, Object>>) requestBody.get("MergeInfos");
- String VideoUrl = (String) requestBody.get("VideoUrl");
- Integer SwapModelType = (Integer) requestBody.get("SwapModelType");
- /*
- https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-1.png
- https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg
- https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-1.png
- https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-2.png
- */
- // String imgUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg";
- // String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";
- Credential cred = new Credential(SECRET_ID, SECRET_KEY);
- // FacefusionClient client = new FacefusionClient(cred, "ap-guangzhou");
- CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
- JSONObject param = new JSONObject();
- JSONArray paramMergeInfos = JSONUtil.parseArray(MergeInfos);
- JSONArray paramTemplateInfos = JSONUtil.parseArray(TemplateInfos);
- System.out.println("paramMergeInfos:");
- System.out.println(paramMergeInfos);
- System.out.println("paramTemplateInfos:");
- System.out.println(paramTemplateInfos);
- param.set("MergeInfos", MergeInfos);
- param.set("TemplateInfos", TemplateInfos);
- param.set("VideoUrl", VideoUrl);
- param.set("SwapModelType", SwapModelType);
- System.out.println("param:");
- System.out.println(param);
- String resp = client.call("SubmitLongVideoFaceFusionJobPro", JSONUtil.toJsonStr(param));
- System.out.println(resp);
- return resp;
- } catch (TencentCloudSDKException e) {
- System.out.println(e);
- System.out.println(e.getMessage());
- return e.getMessage();
- }
- }
- /**
- * 通过Job Id查询视频人脸融合任务的进度和状态
- */
- @GetMapping("QueryVideoFaceFusionJob")
- public String QueryVideoFaceFusionJob(String JobId) throws TencentCloudSDKException {
- Credential cred = new Credential(SECRET_ID, SECRET_KEY);
- CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
- String param = "{\"JobId\":\"" + JobId + "\"}";
- String resp = client.call("QueryVideoFaceFusionJob", param);
- System.out.println(resp);
- return resp;
- }
- @Value("${file.upload.directory}") // 配置保存文件的目录
- private String uploadDirectory;
- private static final ObjectMapper MAPPER = new ObjectMapper();
- // @Autowired
- // private HttpExchangeService httpExchangeService;
- // @PostMapping("testWebHook")
- // public Result testWebHook(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {
- // System.out.println("------- testWebHook --------");
- //// try {
- //// String requestBody = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
- //// System.out.println(requestBody);
- //// } catch (IOException e) {
- //// e.printStackTrace();
- //// }
- // System.out.println("===========================================");
- // System.out.println("requestBody:");
- // System.out.println(requestBody);
- // System.out.println("----------------------------");
- // System.out.println("requestBody (JSON):");
- // System.out.println(JSONUtil.parseObj(requestBody));
- // System.out.println("----------------------------");
- // String token = request.getHeader("X-Codeup-Token");
- // System.out.println("X-Codeup-Token: " + token);
- // System.out.println("===========================================");
- // return null;
- // }
- //
- @Autowired
- private TestService testService;
- @GetMapping("testThreadPool")
- public String testThreadPool() throws ExecutionException, InterruptedException {
- testService.testThreadPool();
- return "ok";
- }
- @RateLimiting(key = "test", limit = 5, duration = 10)
- @GetMapping("testSemaphore")
- public String testSemaphore() {
- // Semaphore semaphore = new Semaphore(2);
- // try {
- // // 尝试获取一个许可
- // semaphore.acquire();
- // // 模拟服务操作
- // System.out.println("服务被访问,当前活跃线程数:" + semaphore.availablePermits());
- // // 假设服务操作需要一些时间
- // Thread.sleep(5000);
- // } catch (InterruptedException e) {
- // Thread.currentThread().interrupt();
- // System.out.println("线程被中断");
- // } finally {
- // // 释放许可
- // semaphore.release();
- // System.out.println("服务访问结束,释放许可,当前活跃线程数:" + semaphore.availablePermits());
- // }
- return "ok";
- }
- // @Autowired
- // private SysResourceService sysResourceService;
- //
- // @GetMapping("testConsumptionPoint")
- // public Result testConsumptionPoint(String resource_type, String resource_tag) throws IOException {
- // sysResourceService.consumptionPoint(resource_type, resource_tag, null);
- // return Result.success("扣除成功");
- // }
- // @Autowired
- // private SDKTencentCOSService sdkTencentCOSService;
- //
- // @PostMapping("testUploadOrigin")
- // public Result testUploadOrigin(@RequestBody UploadOriginDTO uploadOriginDTO) throws IOException {
- // return Result.success(sdkTencentCOSService.uploadOrigin(uploadOriginDTO));
- // }
- @GetMapping("testLocalPath")
- public Path testLocalPath() {
- return Paths.get(".");
- }
- @GetMapping("testDownloadLocal")
- public String testDownloadLocal() {
- // return ResourceUtil.downloadImage("https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240417/172326_0_2a130824-cffe-4d18-8455-f98c18e4900e.png?Expires=1713432207&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=439TeHWxweXDJ%2FE8mAQ3UQJx7XI%3D");
- return ResourceUtil.downloadImage("http://cos.daoguyujiamcn.com/customer-pipline/1/65119e58-9940-458c-8911-750d23f9fbf1/idcard/b.pdf", uploadDirectory);
- }
- //
- //
- // // 【腾讯云 COS】
- // // 文档中心 > 对象存储 > API 文档 > Object 接口 > 基本操作 > PUT Object
- // // https://cloud.tencent.com/document/product/436/7749
- // // https://github.com/tencentyun/cos-java-sdk-v5/blob/master/src/main/java/com/qcloud/cos/demo/PutObjectDemo.java
- // static COSClient cosClient = createCli();
- //
- // static COSClient createCli() {
- // return createCli("ap-hongkong");
- // }
- //
- // static COSClient createCli(String region) {
- // // 初始化用户身份信息(secretId, secretKey)
- // COSCredentials cred = new BasicCOSCredentials("AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK","IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr");
- // // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
- // ClientConfig clientConfig = new ClientConfig(new Region(region));
- // // 生成cos客户端
- // return new COSClient(cred, clientConfig);
- // }
- //
- // /**
- // * 腾讯云 COS - 上传文件
- // */
- // @GetMapping("testTencentSDK/putObject")
- // public String testTencentSDKPutObject() {
- // String bucketName = "storage-1320301544";
- //
- // // 获取当前日期
- // Date currentDate = new Date();
- // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
- // String dateFolder = dateFormat.format(currentDate);
- //
- // System.out.println("dateFolder: " + dateFolder);
- //
- // String fileName = "README.md";
- // String key = dateFolder + "/" + fileName;
- //
- // String localPath = fileName;
- //
- // // 计算过期时间为 1 分钟后
- // Date currentTime = new Date();
- // long expiresTime = currentTime.getTime() + 60*1000; // 当前时间毫秒数 + 1分钟的毫秒数
- // ObjectMetadata objectMetadata = new ObjectMetadata();
- // objectMetadata.setHeader("expires", new Date(expiresTime));
- //
- // PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));
- // putObjectRequest.withMetadata(objectMetadata);
- //
- // PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
- //
- // System.out.println(putObjectResult.getRequestId());
- //
- // GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
- // COSObject cosObject = cosClient.getObject(getObjectRequest);
- // System.out.println(cosObject.getObjectMetadata().getRequestId());
- //
- // cosClient.shutdown();
- // return "ok";
- // }
- //
- // 文档中心 > SDK 中心 > Java
- // https://cloud.tencent.com/document/sdk/Java
- // 【腾讯云-混元大模型】
- // https://cloud.tencent.com/document/api/1729/101843
- // private final static Charset UTF8 = StandardCharsets.UTF_8;
- //// // 需要设置环境变量 TENCENTCLOUD_SECRET_ID,值为示例的 AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******
- //// private final static String SECRET_ID = "AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK";
- //// // 需要设置环境变量 TENCENTCLOUD_SECRET_KEY,值为示例的 Gu5t9xGARNpq86cd98joQYCN3*******
- //// private final static String SECRET_KEY = "IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr";
- //
- // @Value("tencent.hunyuan.secret-id")
- // private String SECRET_ID;
- // @Value("tencent.hunyuan.secret-key")
- // private String SECRET_KEY;
- //
- //
- // private final static String CT_JSON = "application/json; charset=utf-8";
- // public static byte[] hmac256(byte[] key, String msg) throws Exception {
- // Mac mac = Mac.getInstance("HmacSHA256");
- // SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
- // mac.init(secretKeySpec);
- // return mac.doFinal(msg.getBytes(UTF8));
- // }
- // public static String sha256Hex(String s) throws Exception {
- // MessageDigest md = MessageDigest.getInstance("SHA-256");
- // byte[] d = md.digest(s.getBytes(UTF8));
- // return DatatypeConverter.printHexBinary(d).toLowerCase();
- // }
- // @GetMapping("testTencentSDK/hunyuan")
- // public Result testTencentSDKHunyuan() throws Exception {
- //
- // try {
- // String result = "";
- // Credential cred = new Credential(SECRET_ID, SECRET_KEY);
- // ClientProfile clientProfile = new ClientProfile();
- // HunyuanClient client = new HunyuanClient(cred, "ap-guangzhou", clientProfile);
- //
- // ChatStdRequest req = new ChatStdRequest();
- // Message msg = new Message();
- // msg.setRole("user");
- // msg.setContent("给我一句诗,不超过10个字");
- // req.setMessages(new Message[]{ msg });
- //
- // ChatStdResponse resp = client.ChatStd(req);
- //
- // Gson gson = new GsonBuilder().create();
- // for (SSEResponseModel.SSE e : resp) {
- //
- // System.out.println(e.Data);
- //
- // /**
- // * .Data:
- // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"当然"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":1,"TotalTokens":8}}
- // * e.Data:
- // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"可以"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":2,"TotalTokens":9}}
- // * e.Data:
- // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":","}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":3,"TotalTokens":10}}
- // * e.Data:
- // */
- // JSONObject dataObject = JSONUtil.parseObj(e.Data);
- // JSONArray choicesArray = dataObject.getJSONArray("Choices");
- // if (choicesArray != null && choicesArray.size() > 0) {
- // // 获取第一个元素
- // JSONObject firstChoice = choicesArray.getJSONObject(0);
- // System.out.println("firstChoice:");
- // System.out.println(firstChoice);
- // // 获取 Delta 对象
- // JSONObject deltaObject = firstChoice.getJSONObject("Delta");
- // System.out.println("deltaObject:");
- // System.out.println(deltaObject);
- // // 获取 content 的值
- // String content = deltaObject.getStr("Content");
- // System.out.println("Content: " + content);
- //
- // result += content;
- // System.out.println("result: " + result);
- // System.out.println("---------------------------------------------");
- // }
- // }
- // return Result.success(result);
- //
- // } catch (TencentCloudSDKException e) {
- // e.printStackTrace();
- // }
- // return null;
- // }
- // @GetMapping("testQueue")
- // @QueuingPoll
- // public String testQueue(@RequestParam Integer tenantId, @RequestParam Integer time) throws InterruptedException {
- // Thread currentThread = Thread.currentThread();
- // String threadName = currentThread.getName();
- // System.out.println(threadName + " 开始休眠: " + time);
- // Thread.sleep(time);
- // System.out.println(threadName + " 休眠结束: " + time);
- // return threadName;
- // }
- @GetMapping("testMeitu/login")
- public JSONObject testMeituLogin(String code, String access_key) {
- System.out.println("code: " + code + ", access_key: " + access_key);
- System.out.println("---------------------------------------------------");
- String response = "{\"code\": 0,\"msg\": \"success\", \"data\": {\"id\": \"enjdj328ydhhw3u43yjhdj\", \"name\": \"张三\",\"avatar_url\": \"http://www.**.com/avatar/icon.jpg\"}}";
- JSONObject jsonObject = JSONUtil.parseObj(response);
- return jsonObject;
- }
- @Autowired
- private RedisTemplate redisTemplate;
- @GetMapping("testQueue")
- @QueuingPoll
- public String testQueue(String taskId) {
- redisTemplate.opsForList().rightPush("demoQueue", taskId);
- Long listSize = redisTemplate.opsForList().size("demoQueue");
- System.out.println("队伍总人数: " + listSize);
- List listData = redisTemplate.opsForList().range("demoQueue", 0, -1);
- System.out.println("队伍信息: " + listData.toString() + ", taskId: " + taskId + ", listData.get(0): " + listData.get(0));
- Integer index = 0;
- if (listData.size() == 0 || (listData.size() > 0 && listData.get(0).toString().equals(taskId))) {
- // 创建一个 CompletableFuture 来执行异步任务
- CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
- // 执行业务逻辑
- System.out.println("开始休眠..");
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- System.out.println("休眠结束..");
- //
- Long removeNum = redisTemplate.opsForList().remove("demoQueue", 0, taskId);
- System.out.println("离开队伍: " + removeNum);
- System.out.println("-------------------------------------");
- });
- return "操作成功";
- } else {
- index = listData.indexOf(taskId);
- return "排队中:" + index + " / " + listSize;
- }
- }
- /**
- * 这里多个key用":" 拼接,后续定时任务踢出队列拆分使用。
- * @param keys
- * @return
- */
- public static String buildResourcesSetValue(String... keys){
- return String.join(":",keys);
- }
- // @GetMapping("testQueue")
- // public String testQueue() throws InterruptedException {
- // // 定义Redis信号量,允许的最大并发数为1
- // RSemaphore semaphore = redissonClient.getSemaphore("demoQueue");
- // int maxConcurrentRequests = 2; // 允许的最大并发请求数
- //
- // try {
- // // 尝试获取信号量,设定超时时间为3秒
- // if (!semaphore.tryAcquire(maxConcurrentRequests, 3, TimeUnit.SECONDS)) {
- // // 如果无法获取信号量,说明并发数已满,抛出异常
- // long waitingPosition = getWaitingPosition();
- // throw new CustException("正在排队中,第" + waitingPosition + "位 / 共" + maxConcurrentRequests + "位");
- // }
- // // 执行业务逻辑
- // System.out.println("开始休眠..");
- // Thread.sleep(5000);
- // System.out.println("休眠结束..");
- //
- // } catch (InterruptedException e) {
- // // 处理中断异常
- // throw new CustException("处理中断异常");
- //
- // } finally {
- // // 释放信号量
- //// if (semaphore.isHeldByCurrentThread()) {
- // System.out.println("semaphore:");
- // System.out.println(semaphore);
- // System.out.println(semaphore.isExists());
- // semaphore.release();
- //// }
- // }
- //
- //
- // // 返回结果
- // return "操作成功";
- //
- // }
- //
- // // 获取当前排队位置的方法
- // private long getWaitingPosition() {
- // RScoredSortedSet<Object> scoreSet = redissonClient.getScoredSortedSet("demoQueue");
- //// long queueSize = scoreSet.size();
- //// System.out.println("(getWaitingPosition) queueSize: " + queueSize);
- // long waitingPosition = 0;
- // // 遍历有序集合,计算当前请求之前的请求数量
- // Iterator<Object> iterator = scoreSet.iterator(0);
- // while (iterator.hasNext()) {
- // Object obj = iterator.next();
- // Double score = scoreSet.getScore(obj);
- // if (score > System.currentTimeMillis()) {
- // waitingPosition++;
- // }
- // }
- // return waitingPosition;
- // }
- /* 字符串 转 JSONObject */
- @GetMapping("testJSONObject")
- public JSONObject testGson() {
- String jsonString = " {\"Note\":\"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记\",\"Choices\":[{\"FinishReason\":\"stop\",\"Delta\":{\"Role\":\"assistant\",\"Content\":\"\"}}],\"Created\":1709617106,\"Id\":\"7511d79a-6318-4da1-883a-35c8be97f67f\",\"Usage\":{\"PromptTokens\":7,\"CompletionTokens\":23,\"TotalTokens\":30}}";
- JSONObject jsonObject = JSONUtil.parseObj(jsonString);
- return jsonObject;
- }
- // 【火山引擎】
- // - 公共错误代码
- // https://www.volcengine.com/docs/6369/68677
- // - 获取个性化内容
- // https://www.volcengine.com/docs/6392/75762
- // - 模型广场
- // https://www.volcengine.com/docs/82379/1099503
- // @GetMapping("testHuoshanSDK")
- // public String testHuoShanSDK() throws Exception {
- // // 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
- // String ak = "AKLTMjM2OTNmNTViNGQ3NDM0NmI1YjU4MmU2ZjY5YzEwM2I";
- // String sk = "WlRZMk5qRTJOR1ZrTURnMk5EVmhZVGc1TmpVeE4yUTJNelkzWXpVeU1XVQ==";
- //
- // BusinessSecurityService businessSecurityService = BusinessSecurityServiceImpl.getInstance();
- // // call below method if you dont set ak and sk in ~/.volc/config
- //
- // businessSecurityService.setAccessKey(ak);
- // businessSecurityService.setSecretKey(sk);
- // // risk detection
- // try {
- // RiskDetectionRequest riskDetectionRequest = new RiskDetectionRequest();
- //// riskDetectionRequest.setLimit(3);
- //
- // RiskDetectionResponse riskDetectionResponse = businessSecurityService.RiskDetection(riskDetectionRequest);
- // System.out.println(JSON.toJSONString(riskDetectionResponse));
- // } catch (Exception e) {
- // e.printStackTrace();
- // }
- //
- // return "1";
- // }
- // @GetMapping("testMeituSDK")
- // public SdkResponseDTO.Result testMeituSDK() throws URISyntaxException {
- // //使用前需提前申请 AccessKey 和 secret,具体获取,请对接商务
- // String accessKey = "306129caf4574016be9c09a5b0ecdcad";
- // String secret = "a202a3f4f0a844109cea84af79ad9b40";
- //
- // // 创建AiClient实例
- // AiClient aiClient = new AiClient(accessKey,secret);
- //
- // // 【美图AI - 文生图】
- // // https://ai.meitu.com/doc/?id=228&type=api&lang=zh
- //
- // // 文生图的请求对象
- // InferenceParamsDTO inferenceParamsDTO = new InferenceParamsDTO();
- // // 推理业务配置中获取中约定的模型平台
- // inferenceParamsDTO.setModelPlatform("diffusers");
- // // 推理业务配置中获取的模型
- // inferenceParamsDTO.setModel("braBeautifulRealistic_V5_diffusers_v0.1.zip");
- // // 提示词
- // inferenceParamsDTO.setPrompt("a girl");
- // // 方向提示词
- // inferenceParamsDTO.setNegativePrompt("easy negative");
- // // 推理业务配置中获取中约定的高
- // inferenceParamsDTO.setHeight(512);
- // // 推理业务配置中获取中约定的宽
- // inferenceParamsDTO.setHeight(512);
- // // 推理提交推理任务,并等待返回推理图片地址
- // SdkResponseDTO.Result result = aiClient.inference(inferenceParamsDTO);
- // return result;
- // }
- @GetMapping("testWordExport")
- public Map<String, Object> SimpleWordExport() {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("title", "Easypoi 标题");
- map.put("content", "JueYue 内容,在家也能享受绿色健康美味!用纯天然无添加剂的食材,带给你和家人最纯净的美味。从选购新鲜食材到烘焙出炉,每一步都充满温馨与乐趣。让我们一起回归自然,享受绿色健康的蛋糕时光!");
- try {
- XWPFDocument doc = WordExportUtil.exportWord07("D:/excel/template.docx", map);
- FileOutputStream fos = new FileOutputStream("D:/excel/simple.docx");
- doc.write(fos);
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return map;
- }
- @GetMapping("testGetUUID")
- public String testGetUUID() {
- return UUID.randomUUID().toString();
- }
- @GetMapping("testGetShortUUID")
- public String testGetShortUUID(Integer length) {
- // return UUID.randomUUID().toString()
- // .replace("-", "")
- // .substring(0, length);
- return IdUtil.simpleUUID().substring(0, length);
- }
- /**
- * BCrypt算法进行加密
- */
- @GetMapping("testPassword")
- public String testPassword(String value) {
- String password = Optional.ofNullable(value).orElse("123456");
- BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
- String encodedPassword = encoder.encode(password);
- boolean matched = encoder.matches(password, encodedPassword);
- return "Value: " + value + "\nencodedPassword: " + encodedPassword + "\nmatched: " + matched;
- }
- /**
- * 使用 MD5Util 工具类
- */
- @GetMapping("testMD5")
- public String testMD5(String value) throws NoSuchAlgorithmException {
- String password = Optional.ofNullable(value).orElse("123456");
- String version = "0.0.48";
- return "Value: " + value + "\n" +
- "MD5: " + MD5Util.encrypt(password) + "\n" +
- "Version: " + version;
- }
- @GetMapping("/testJSON")
- public String testJSON() throws JsonProcessingException {
- Integer[] a = MAPPER.readValue("1,2", Integer[].class);
- System.out.println("a: ");
- System.out.println(a);
- return "1";
- }
- @GetMapping("testFont")
- public String[] testFont() {
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- String[] fontNames = ge.getAvailableFontFamilyNames();
- for (String fontName : fontNames) {
- System.out.println(fontName);
- }
- return fontNames;
- }
- /**
- * Redisson 加锁
- * @return
- */
- @Lazy
- @Autowired
- RedissonClient redissonClient;
- @GetMapping("testRedisson")
- public String testGetRedisson() throws InterruptedException {
- RLock lock = redissonClient.getLock("my-lock");
- lock.tryLock(3, TimeUnit.SECONDS); // 阻塞式等待。默认加的锁是30s时间
- try {
- // 1、锁的自动续期,运行期间自动给锁续上新的30s,无需担心业务时间长,锁过期会自动被释放
- // 2、加锁的业务只要运行完成,就不会给当前锁续期,即使不手动释放锁,锁默认在30s后自动释放,避免死锁
- System.out.println("加锁成功,执行业务代码..."+Thread.currentThread().getId());
- Thread.sleep(3000);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- System.out.println("释放锁..."+Thread.currentThread().getId());
- lock.unlock();
- }
- return "get lock!";
- }
- /**
- * Redisson 一般用于商品秒杀活动:
- */
- /*
- @Component
- public class DistributedLockExample {
- @Autowired
- private Redisson redisson;
- private RLock distributedLock;
- @PostConstruct
- private void init() {
- distributedLock = redisson.getLock("myDistributedLock");
- }
- public void performOperation() {
- try {
- // 尝试获取分布式锁,最多等待10秒
- boolean lockAcquired = distributedLock.tryLock(10, TimeUnit.SECONDS);
- if (lockAcquired) {
- // 获取锁成功,执行需要加锁的业务逻辑
- // ...
- } else {
- // 获取锁失败,处理异常情况
- // ...
- }
- } catch (InterruptedException e) {
- // 处理中断异常
- // ...
- } finally {
- // 释放分布式锁
- distributedLock.unlock();
- }
- }
- }
- */
- public static Object resource1 = new Object();
- public static Object resource2 = new Object();
- @GetMapping("testDeadLock")
- public String testDeadLock() {
- RLock lock = redissonClient.getLock("thread-lock");
- // 线程1
- new Thread(() -> {
- //System.out.println("------- lock thread-1 -------");
- lock.lock();
- synchronized (resource2) {
- System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- synchronized (resource1) {
- System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
- lock.unlock();
- }
- }
- }).start();
- // 线程2
- new Thread(() -> {
- //System.out.println("------- lock thread-2 -------");
- lock.lock();
- synchronized (resource1) {
- System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- synchronized (resource2) {
- System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
- lock.unlock();
- }
- }
- }).start();
- return "ok";
- }
- }
|