TestController.java 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. package com.backendsys.modules;
  2. import cn.hutool.core.util.IdUtil;
  3. import cn.hutool.json.JSONArray;
  4. import cn.hutool.json.JSONObject;
  5. import cn.hutool.json.JSONUtil;
  6. import com.backendsys.aspect.RateLimiting;
  7. import com.backendsys.aspect.QueuingPoll;
  8. import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
  9. import com.backendsys.modules.common.utils.Result;
  10. import com.backendsys.modules.sdk.baidu.yunapp.entity.ExecuteScriptParams;
  11. import com.backendsys.modules.sdk.baidu.yunapp.service.YunappService;
  12. import com.backendsys.modules.sdk.volcengine.entity.VisualFaceSwapV2;
  13. import com.backendsys.modules.sdk.volcengine.service.VolcengineService;
  14. import com.backendsys.service.TestService;
  15. import com.backendsys.utils.ResourceUtil;
  16. import com.fasterxml.jackson.core.JsonProcessingException;
  17. import com.fasterxml.jackson.databind.ObjectMapper;
  18. import cn.afterturn.easypoi.word.WordExportUtil;
  19. import com.backendsys.utils.MD5Util;
  20. import com.tencentcloudapi.common.Credential;
  21. //import io.github.pigmesh.ai.deepseek.core.DeepSeekClientImpl;
  22. //import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException;
  23. //import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
  24. import com.volcengine.service.visual.IVisualService;
  25. import com.volcengine.service.visual.impl.VisualServiceImpl;
  26. import jakarta.servlet.ServletContext;
  27. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  28. import org.redisson.api.*;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.beans.factory.annotation.Value;
  31. import org.springframework.context.annotation.Lazy;
  32. import org.springframework.data.redis.core.RedisTemplate;
  33. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  34. import org.springframework.web.bind.annotation.*;
  35. import java.awt.*;
  36. import java.io.*;
  37. import java.nio.file.Path;
  38. import java.nio.file.Paths;
  39. import java.security.NoSuchAlgorithmException;
  40. import java.util.*;
  41. import java.util.List;
  42. import java.util.concurrent.CompletableFuture;
  43. import java.util.concurrent.ExecutionException;
  44. import java.util.concurrent.TimeUnit;
  45. //import com.tencentcloudapi.facefusion.v20181201.FacefusionClient;
  46. //import com.tencentcloudapi.facefusion.v20181201.models.*;
  47. //import com.tencentcloudapi.facefusion.v20220927.FacefusionClient;
  48. //import com.tencentcloudapi.facefusion.v20220927.models.*;
  49. //import com.tencentcloudapi.common.Credential;
  50. //import com.tencentcloudapi.common.profile.ClientProfile;
  51. //import com.tencentcloudapi.common.profile.HttpProfile;
  52. //import com.tencentcloudapi.common.exception.TencentCloudSDKException;
  53. //import com.tencentcloudapi.facefusion.v20181201.FacefusionClient;
  54. //import com.tencentcloudapi.facefusion.v20181201.models.*;
  55. import com.tencentcloudapi.common.CommonClient;
  56. import com.tencentcloudapi.common.exception.TencentCloudSDKException;
  57. @RestController
  58. @RequestMapping("/api/test")
  59. @SuppressWarnings({"rawtypes", "unchecked"})
  60. public class TestController {
  61. @Value("${tencent.facefusion.secret-id}")
  62. private String SECRET_ID;
  63. @Value("${tencent.facefusion.secret-key}")
  64. private String SECRET_KEY;
  65. // @Autowired
  66. // private DeepSeekClientImpl deepSeekClient;
  67. //
  68. // // https://javaai.pig4cloud.com/deepseek/quickstart
  69. // // sse 流式返回
  70. // @GetMapping(value = "/deepseek/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  71. // public Flux<ChatCompletionResponse> chat(String prompt) {
  72. // try {
  73. // Flux<ChatCompletionResponse> flux = deepSeekClient.chatFluxCompletion(prompt);
  74. // return flux;
  75. // } catch (OpenAiHttpException e) {
  76. // throw new CustException(e.getMessage());
  77. // }
  78. // }
  79. // // 进阶配置(多轮对话)
  80. // @GetMapping(value = "/chat/advanced", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  81. // public Flux<ChatCompletionResponse> advancedChat(String prompt) {
  82. // ChatCompletionRequest request = ChatCompletionRequest.builder()
  83. // .model(ChatCompletionModel.DEEPSEEK_REASONER) // 指定推理模型
  84. // .addUserMessage(prompt) // 用户当前问题
  85. // .addAssistantMessage("上轮对话结果") // 历史助手回复
  86. // .addSystemMessage("你是一名AI助理") // 系统角色设定
  87. // .maxTokens(1000) // 最大生成 token 数
  88. // .temperature(0.7) // 生成多样性控制
  89. // .tools(yourFunctionTools) // Function Calling 工具
  90. // .responseFormat(ChatResponseFormat.JSON) // 结构化响应
  91. // .build();
  92. //
  93. // return deepSeekClient.chatFluxCompletion(request);
  94. // }
  95. @Autowired
  96. private VolcengineService volcengineService;
  97. @PostMapping("/FaceSwapV2")
  98. public Result FaceSwapV2(@RequestBody VisualFaceSwapV2 visualFaceSwapV2) {
  99. System.out.println(visualFaceSwapV2);
  100. return Result.success().put("data", volcengineService.FaceSwapV2(visualFaceSwapV2));
  101. }
  102. @Autowired
  103. private ServletContext servletContext;
  104. @GetMapping("/tomcat-version")
  105. public String getTomcatVersion() {
  106. String serverInfo = servletContext.getServerInfo();
  107. return "当前Tomcat版本: " + serverInfo;
  108. }
  109. /*
  110. // SubmitMediaModeration 提交审核任务
  111. // DescribeMediaModeration 查询审核结果
  112. // SubmitLongVideoFaceFusionJobPro 视频人脸融合异步处理任务,成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
  113. // QueryVideoFaceFusionJob 通过Job Id查询视频人脸融合任务的进度和状态
  114. */
  115. /**
  116. * [腾讯云-人脸融合] 提交审核任务 (视频)
  117. */
  118. @PostMapping("SubmitMediaModeration")
  119. public String SubmitMediaModeration(@RequestBody Map<String, Object> requestBody) throws TencentCloudSDKException {
  120. String videoUrl = (String) requestBody.get("videoUrl");
  121. // String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";
  122. Credential cred = new Credential(SECRET_ID, SECRET_KEY);
  123. CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
  124. String param = "{\"VideoUrl\":\"" + videoUrl + "\"}";
  125. String resp = client.call("SubmitMediaModeration", param);
  126. System.out.println(resp);
  127. return resp;
  128. }
  129. /**
  130. * [腾讯云-人脸融合] 查询审核结果
  131. */
  132. @GetMapping("DescribeMediaModeration")
  133. public String DescribeMediaModeration(String JobId) throws TencentCloudSDKException {
  134. Credential cred = new Credential(SECRET_ID, SECRET_KEY);
  135. CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
  136. String param = "{\"JobId\":\"" + JobId + "\"}";
  137. String resp = client.call("DescribeMediaModeration", param);
  138. System.out.println(resp);
  139. return resp;
  140. }
  141. /**
  142. * 视频人脸融合异步处理任务,成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
  143. */
  144. @PostMapping("/SubmitLongVideoFaceFusionJobPro")
  145. public String SubmitLongVideoFaceFusionJobPro(@RequestBody Map<String, Object> requestBody) {
  146. try {
  147. // 从Map中获取参数
  148. List<Map<String, Object>> TemplateInfos = (List<Map<String, Object>>) requestBody.get("TemplateInfos");
  149. List<Map<String, Object>> MergeInfos = (List<Map<String, Object>>) requestBody.get("MergeInfos");
  150. String VideoUrl = (String) requestBody.get("VideoUrl");
  151. Integer SwapModelType = (Integer) requestBody.get("SwapModelType");
  152. /*
  153. https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-1.png
  154. https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg
  155. https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-1.png
  156. https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-2.png
  157. */
  158. // String imgUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg";
  159. // String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";
  160. Credential cred = new Credential(SECRET_ID, SECRET_KEY);
  161. // FacefusionClient client = new FacefusionClient(cred, "ap-guangzhou");
  162. CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
  163. JSONObject param = new JSONObject();
  164. JSONArray paramMergeInfos = JSONUtil.parseArray(MergeInfos);
  165. JSONArray paramTemplateInfos = JSONUtil.parseArray(TemplateInfos);
  166. System.out.println("paramMergeInfos:");
  167. System.out.println(paramMergeInfos);
  168. System.out.println("paramTemplateInfos:");
  169. System.out.println(paramTemplateInfos);
  170. param.set("MergeInfos", MergeInfos);
  171. param.set("TemplateInfos", TemplateInfos);
  172. param.set("VideoUrl", VideoUrl);
  173. param.set("SwapModelType", SwapModelType);
  174. System.out.println("param:");
  175. System.out.println(param);
  176. String resp = client.call("SubmitLongVideoFaceFusionJobPro", JSONUtil.toJsonStr(param));
  177. System.out.println(resp);
  178. return resp;
  179. } catch (TencentCloudSDKException e) {
  180. System.out.println(e);
  181. System.out.println(e.getMessage());
  182. return e.getMessage();
  183. }
  184. }
  185. /**
  186. * 通过Job Id查询视频人脸融合任务的进度和状态
  187. */
  188. @GetMapping("QueryVideoFaceFusionJob")
  189. public String QueryVideoFaceFusionJob(String JobId) throws TencentCloudSDKException {
  190. Credential cred = new Credential(SECRET_ID, SECRET_KEY);
  191. CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");
  192. String param = "{\"JobId\":\"" + JobId + "\"}";
  193. String resp = client.call("QueryVideoFaceFusionJob", param);
  194. System.out.println(resp);
  195. return resp;
  196. }
  197. @Value("${file.upload.directory}") // 配置保存文件的目录
  198. private String uploadDirectory;
  199. private static final ObjectMapper MAPPER = new ObjectMapper();
  200. // @Autowired
  201. // private HttpExchangeService httpExchangeService;
  202. // @PostMapping("testWebHook")
  203. // public Result testWebHook(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {
  204. // System.out.println("------- testWebHook --------");
  205. //// try {
  206. //// String requestBody = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
  207. //// System.out.println(requestBody);
  208. //// } catch (IOException e) {
  209. //// e.printStackTrace();
  210. //// }
  211. // System.out.println("===========================================");
  212. // System.out.println("requestBody:");
  213. // System.out.println(requestBody);
  214. // System.out.println("----------------------------");
  215. // System.out.println("requestBody (JSON):");
  216. // System.out.println(JSONUtil.parseObj(requestBody));
  217. // System.out.println("----------------------------");
  218. // String token = request.getHeader("X-Codeup-Token");
  219. // System.out.println("X-Codeup-Token: " + token);
  220. // System.out.println("===========================================");
  221. // return null;
  222. // }
  223. //
  224. @Autowired
  225. private TestService testService;
  226. @GetMapping("testThreadPool")
  227. public String testThreadPool() throws ExecutionException, InterruptedException {
  228. testService.testThreadPool();
  229. return "ok";
  230. }
  231. @RateLimiting(key = "test", limit = 5, duration = 10)
  232. @GetMapping("testSemaphore")
  233. public String testSemaphore() {
  234. // Semaphore semaphore = new Semaphore(2);
  235. // try {
  236. // // 尝试获取一个许可
  237. // semaphore.acquire();
  238. // // 模拟服务操作
  239. // System.out.println("服务被访问,当前活跃线程数:" + semaphore.availablePermits());
  240. // // 假设服务操作需要一些时间
  241. // Thread.sleep(5000);
  242. // } catch (InterruptedException e) {
  243. // Thread.currentThread().interrupt();
  244. // System.out.println("线程被中断");
  245. // } finally {
  246. // // 释放许可
  247. // semaphore.release();
  248. // System.out.println("服务访问结束,释放许可,当前活跃线程数:" + semaphore.availablePermits());
  249. // }
  250. return "ok";
  251. }
  252. // @Autowired
  253. // private SysResourceService sysResourceService;
  254. //
  255. // @GetMapping("testConsumptionPoint")
  256. // public Result testConsumptionPoint(String resource_type, String resource_tag) throws IOException {
  257. // sysResourceService.consumptionPoint(resource_type, resource_tag, null);
  258. // return Result.success("扣除成功");
  259. // }
  260. // @Autowired
  261. // private SDKTencentCOSService sdkTencentCOSService;
  262. //
  263. // @PostMapping("testUploadOrigin")
  264. // public Result testUploadOrigin(@RequestBody UploadOriginDTO uploadOriginDTO) throws IOException {
  265. // return Result.success(sdkTencentCOSService.uploadOrigin(uploadOriginDTO));
  266. // }
  267. @GetMapping("testLocalPath")
  268. public Path testLocalPath() {
  269. return Paths.get(".");
  270. }
  271. @GetMapping("testDownloadLocal")
  272. public String testDownloadLocal() {
  273. // 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");
  274. return ResourceUtil.downloadImage("http://cos.daoguyujiamcn.com/customer-pipline/1/65119e58-9940-458c-8911-750d23f9fbf1/idcard/b.pdf", uploadDirectory);
  275. }
  276. //
  277. //
  278. // // 【腾讯云 COS】
  279. // // 文档中心 > 对象存储 > API 文档 > Object 接口 > 基本操作 > PUT Object
  280. // // https://cloud.tencent.com/document/product/436/7749
  281. // // https://github.com/tencentyun/cos-java-sdk-v5/blob/master/src/main/java/com/qcloud/cos/demo/PutObjectDemo.java
  282. // static COSClient cosClient = createCli();
  283. //
  284. // static COSClient createCli() {
  285. // return createCli("ap-hongkong");
  286. // }
  287. //
  288. // static COSClient createCli(String region) {
  289. // // 初始化用户身份信息(secretId, secretKey)
  290. // COSCredentials cred = new BasicCOSCredentials("AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK","IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr");
  291. // // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
  292. // ClientConfig clientConfig = new ClientConfig(new Region(region));
  293. // // 生成cos客户端
  294. // return new COSClient(cred, clientConfig);
  295. // }
  296. //
  297. // /**
  298. // * 腾讯云 COS - 上传文件
  299. // */
  300. // @GetMapping("testTencentSDK/putObject")
  301. // public String testTencentSDKPutObject() {
  302. // String bucketName = "storage-1320301544";
  303. //
  304. // // 获取当前日期
  305. // Date currentDate = new Date();
  306. // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
  307. // String dateFolder = dateFormat.format(currentDate);
  308. //
  309. // System.out.println("dateFolder: " + dateFolder);
  310. //
  311. // String fileName = "README.md";
  312. // String key = dateFolder + "/" + fileName;
  313. //
  314. // String localPath = fileName;
  315. //
  316. // // 计算过期时间为 1 分钟后
  317. // Date currentTime = new Date();
  318. // long expiresTime = currentTime.getTime() + 60*1000; // 当前时间毫秒数 + 1分钟的毫秒数
  319. // ObjectMetadata objectMetadata = new ObjectMetadata();
  320. // objectMetadata.setHeader("expires", new Date(expiresTime));
  321. //
  322. // PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));
  323. // putObjectRequest.withMetadata(objectMetadata);
  324. //
  325. // PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
  326. //
  327. // System.out.println(putObjectResult.getRequestId());
  328. //
  329. // GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
  330. // COSObject cosObject = cosClient.getObject(getObjectRequest);
  331. // System.out.println(cosObject.getObjectMetadata().getRequestId());
  332. //
  333. // cosClient.shutdown();
  334. // return "ok";
  335. // }
  336. //
  337. // 文档中心 > SDK 中心 > Java
  338. // https://cloud.tencent.com/document/sdk/Java
  339. // 【腾讯云-混元大模型】
  340. // https://cloud.tencent.com/document/api/1729/101843
  341. // private final static Charset UTF8 = StandardCharsets.UTF_8;
  342. //// // 需要设置环境变量 TENCENTCLOUD_SECRET_ID,值为示例的 AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******
  343. //// private final static String SECRET_ID = "AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK";
  344. //// // 需要设置环境变量 TENCENTCLOUD_SECRET_KEY,值为示例的 Gu5t9xGARNpq86cd98joQYCN3*******
  345. //// private final static String SECRET_KEY = "IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr";
  346. //
  347. // @Value("tencent.hunyuan.secret-id")
  348. // private String SECRET_ID;
  349. // @Value("tencent.hunyuan.secret-key")
  350. // private String SECRET_KEY;
  351. //
  352. //
  353. // private final static String CT_JSON = "application/json; charset=utf-8";
  354. // public static byte[] hmac256(byte[] key, String msg) throws Exception {
  355. // Mac mac = Mac.getInstance("HmacSHA256");
  356. // SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
  357. // mac.init(secretKeySpec);
  358. // return mac.doFinal(msg.getBytes(UTF8));
  359. // }
  360. // public static String sha256Hex(String s) throws Exception {
  361. // MessageDigest md = MessageDigest.getInstance("SHA-256");
  362. // byte[] d = md.digest(s.getBytes(UTF8));
  363. // return DatatypeConverter.printHexBinary(d).toLowerCase();
  364. // }
  365. // @GetMapping("testTencentSDK/hunyuan")
  366. // public Result testTencentSDKHunyuan() throws Exception {
  367. //
  368. // try {
  369. // String result = "";
  370. // Credential cred = new Credential(SECRET_ID, SECRET_KEY);
  371. // ClientProfile clientProfile = new ClientProfile();
  372. // HunyuanClient client = new HunyuanClient(cred, "ap-guangzhou", clientProfile);
  373. //
  374. // ChatStdRequest req = new ChatStdRequest();
  375. // Message msg = new Message();
  376. // msg.setRole("user");
  377. // msg.setContent("给我一句诗,不超过10个字");
  378. // req.setMessages(new Message[]{ msg });
  379. //
  380. // ChatStdResponse resp = client.ChatStd(req);
  381. //
  382. // Gson gson = new GsonBuilder().create();
  383. // for (SSEResponseModel.SSE e : resp) {
  384. //
  385. // System.out.println(e.Data);
  386. //
  387. // /**
  388. // * .Data:
  389. // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"当然"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":1,"TotalTokens":8}}
  390. // * e.Data:
  391. // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"可以"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":2,"TotalTokens":9}}
  392. // * e.Data:
  393. // * {"Note":"以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":","}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":3,"TotalTokens":10}}
  394. // * e.Data:
  395. // */
  396. // JSONObject dataObject = JSONUtil.parseObj(e.Data);
  397. // JSONArray choicesArray = dataObject.getJSONArray("Choices");
  398. // if (choicesArray != null && choicesArray.size() > 0) {
  399. // // 获取第一个元素
  400. // JSONObject firstChoice = choicesArray.getJSONObject(0);
  401. // System.out.println("firstChoice:");
  402. // System.out.println(firstChoice);
  403. // // 获取 Delta 对象
  404. // JSONObject deltaObject = firstChoice.getJSONObject("Delta");
  405. // System.out.println("deltaObject:");
  406. // System.out.println(deltaObject);
  407. // // 获取 content 的值
  408. // String content = deltaObject.getStr("Content");
  409. // System.out.println("Content: " + content);
  410. //
  411. // result += content;
  412. // System.out.println("result: " + result);
  413. // System.out.println("---------------------------------------------");
  414. // }
  415. // }
  416. // return Result.success(result);
  417. //
  418. // } catch (TencentCloudSDKException e) {
  419. // e.printStackTrace();
  420. // }
  421. // return null;
  422. // }
  423. // @GetMapping("testQueue")
  424. // @QueuingPoll
  425. // public String testQueue(@RequestParam Integer tenantId, @RequestParam Integer time) throws InterruptedException {
  426. // Thread currentThread = Thread.currentThread();
  427. // String threadName = currentThread.getName();
  428. // System.out.println(threadName + " 开始休眠: " + time);
  429. // Thread.sleep(time);
  430. // System.out.println(threadName + " 休眠结束: " + time);
  431. // return threadName;
  432. // }
  433. @GetMapping("testMeitu/login")
  434. public JSONObject testMeituLogin(String code, String access_key) {
  435. System.out.println("code: " + code + ", access_key: " + access_key);
  436. System.out.println("---------------------------------------------------");
  437. String response = "{\"code\": 0,\"msg\": \"success\", \"data\": {\"id\": \"enjdj328ydhhw3u43yjhdj\", \"name\": \"张三\",\"avatar_url\": \"http://www.**.com/avatar/icon.jpg\"}}";
  438. JSONObject jsonObject = JSONUtil.parseObj(response);
  439. return jsonObject;
  440. }
  441. @Autowired
  442. private RedisTemplate redisTemplate;
  443. @GetMapping("testQueue")
  444. @QueuingPoll
  445. public String testQueue(String taskId) {
  446. redisTemplate.opsForList().rightPush("demoQueue", taskId);
  447. Long listSize = redisTemplate.opsForList().size("demoQueue");
  448. System.out.println("队伍总人数: " + listSize);
  449. List listData = redisTemplate.opsForList().range("demoQueue", 0, -1);
  450. System.out.println("队伍信息: " + listData.toString() + ", taskId: " + taskId + ", listData.get(0): " + listData.get(0));
  451. Integer index = 0;
  452. if (listData.size() == 0 || (listData.size() > 0 && listData.get(0).toString().equals(taskId))) {
  453. // 创建一个 CompletableFuture 来执行异步任务
  454. CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
  455. // 执行业务逻辑
  456. System.out.println("开始休眠..");
  457. try {
  458. Thread.sleep(5000);
  459. } catch (InterruptedException e) {
  460. throw new RuntimeException(e);
  461. }
  462. System.out.println("休眠结束..");
  463. //
  464. Long removeNum = redisTemplate.opsForList().remove("demoQueue", 0, taskId);
  465. System.out.println("离开队伍: " + removeNum);
  466. System.out.println("-------------------------------------");
  467. });
  468. return "操作成功";
  469. } else {
  470. index = listData.indexOf(taskId);
  471. return "排队中:" + index + " / " + listSize;
  472. }
  473. }
  474. /**
  475. * 这里多个key用":" 拼接,后续定时任务踢出队列拆分使用。
  476. * @param keys
  477. * @return
  478. */
  479. public static String buildResourcesSetValue(String... keys){
  480. return String.join(":",keys);
  481. }
  482. // @GetMapping("testQueue")
  483. // public String testQueue() throws InterruptedException {
  484. // // 定义Redis信号量,允许的最大并发数为1
  485. // RSemaphore semaphore = redissonClient.getSemaphore("demoQueue");
  486. // int maxConcurrentRequests = 2; // 允许的最大并发请求数
  487. //
  488. // try {
  489. // // 尝试获取信号量,设定超时时间为3秒
  490. // if (!semaphore.tryAcquire(maxConcurrentRequests, 3, TimeUnit.SECONDS)) {
  491. // // 如果无法获取信号量,说明并发数已满,抛出异常
  492. // long waitingPosition = getWaitingPosition();
  493. // throw new CustException("正在排队中,第" + waitingPosition + "位 / 共" + maxConcurrentRequests + "位");
  494. // }
  495. // // 执行业务逻辑
  496. // System.out.println("开始休眠..");
  497. // Thread.sleep(5000);
  498. // System.out.println("休眠结束..");
  499. //
  500. // } catch (InterruptedException e) {
  501. // // 处理中断异常
  502. // throw new CustException("处理中断异常");
  503. //
  504. // } finally {
  505. // // 释放信号量
  506. //// if (semaphore.isHeldByCurrentThread()) {
  507. // System.out.println("semaphore:");
  508. // System.out.println(semaphore);
  509. // System.out.println(semaphore.isExists());
  510. // semaphore.release();
  511. //// }
  512. // }
  513. //
  514. //
  515. // // 返回结果
  516. // return "操作成功";
  517. //
  518. // }
  519. //
  520. // // 获取当前排队位置的方法
  521. // private long getWaitingPosition() {
  522. // RScoredSortedSet<Object> scoreSet = redissonClient.getScoredSortedSet("demoQueue");
  523. //// long queueSize = scoreSet.size();
  524. //// System.out.println("(getWaitingPosition) queueSize: " + queueSize);
  525. // long waitingPosition = 0;
  526. // // 遍历有序集合,计算当前请求之前的请求数量
  527. // Iterator<Object> iterator = scoreSet.iterator(0);
  528. // while (iterator.hasNext()) {
  529. // Object obj = iterator.next();
  530. // Double score = scoreSet.getScore(obj);
  531. // if (score > System.currentTimeMillis()) {
  532. // waitingPosition++;
  533. // }
  534. // }
  535. // return waitingPosition;
  536. // }
  537. /* 字符串 转 JSONObject */
  538. @GetMapping("testJSONObject")
  539. public JSONObject testGson() {
  540. 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}}";
  541. JSONObject jsonObject = JSONUtil.parseObj(jsonString);
  542. return jsonObject;
  543. }
  544. // 【火山引擎】
  545. // - 公共错误代码
  546. // https://www.volcengine.com/docs/6369/68677
  547. // - 获取个性化内容
  548. // https://www.volcengine.com/docs/6392/75762
  549. // - 模型广场
  550. // https://www.volcengine.com/docs/82379/1099503
  551. // @GetMapping("testHuoshanSDK")
  552. // public String testHuoShanSDK() throws Exception {
  553. // // 注意示例代码安全,代码泄漏会导致AK/SK泄漏,有极大的安全风险。
  554. // String ak = "AKLTMjM2OTNmNTViNGQ3NDM0NmI1YjU4MmU2ZjY5YzEwM2I";
  555. // String sk = "WlRZMk5qRTJOR1ZrTURnMk5EVmhZVGc1TmpVeE4yUTJNelkzWXpVeU1XVQ==";
  556. //
  557. // BusinessSecurityService businessSecurityService = BusinessSecurityServiceImpl.getInstance();
  558. // // call below method if you dont set ak and sk in ~/.volc/config
  559. //
  560. // businessSecurityService.setAccessKey(ak);
  561. // businessSecurityService.setSecretKey(sk);
  562. // // risk detection
  563. // try {
  564. // RiskDetectionRequest riskDetectionRequest = new RiskDetectionRequest();
  565. //// riskDetectionRequest.setLimit(3);
  566. //
  567. // RiskDetectionResponse riskDetectionResponse = businessSecurityService.RiskDetection(riskDetectionRequest);
  568. // System.out.println(JSON.toJSONString(riskDetectionResponse));
  569. // } catch (Exception e) {
  570. // e.printStackTrace();
  571. // }
  572. //
  573. // return "1";
  574. // }
  575. // @GetMapping("testMeituSDK")
  576. // public SdkResponseDTO.Result testMeituSDK() throws URISyntaxException {
  577. // //使用前需提前申请 AccessKey 和 secret,具体获取,请对接商务
  578. // String accessKey = "306129caf4574016be9c09a5b0ecdcad";
  579. // String secret = "a202a3f4f0a844109cea84af79ad9b40";
  580. //
  581. // // 创建AiClient实例
  582. // AiClient aiClient = new AiClient(accessKey,secret);
  583. //
  584. // // 【美图AI - 文生图】
  585. // // https://ai.meitu.com/doc/?id=228&type=api&lang=zh
  586. //
  587. // // 文生图的请求对象
  588. // InferenceParamsDTO inferenceParamsDTO = new InferenceParamsDTO();
  589. // // 推理业务配置中获取中约定的模型平台
  590. // inferenceParamsDTO.setModelPlatform("diffusers");
  591. // // 推理业务配置中获取的模型
  592. // inferenceParamsDTO.setModel("braBeautifulRealistic_V5_diffusers_v0.1.zip");
  593. // // 提示词
  594. // inferenceParamsDTO.setPrompt("a girl");
  595. // // 方向提示词
  596. // inferenceParamsDTO.setNegativePrompt("easy negative");
  597. // // 推理业务配置中获取中约定的高
  598. // inferenceParamsDTO.setHeight(512);
  599. // // 推理业务配置中获取中约定的宽
  600. // inferenceParamsDTO.setHeight(512);
  601. // // 推理提交推理任务,并等待返回推理图片地址
  602. // SdkResponseDTO.Result result = aiClient.inference(inferenceParamsDTO);
  603. // return result;
  604. // }
  605. @GetMapping("testWordExport")
  606. public Map<String, Object> SimpleWordExport() {
  607. Map<String, Object> map = new HashMap<String, Object>();
  608. map.put("title", "Easypoi 标题");
  609. map.put("content", "JueYue 内容,在家也能享受绿色健康美味!用纯天然无添加剂的食材,带给你和家人最纯净的美味。从选购新鲜食材到烘焙出炉,每一步都充满温馨与乐趣。让我们一起回归自然,享受绿色健康的蛋糕时光!");
  610. try {
  611. XWPFDocument doc = WordExportUtil.exportWord07("D:/excel/template.docx", map);
  612. FileOutputStream fos = new FileOutputStream("D:/excel/simple.docx");
  613. doc.write(fos);
  614. fos.close();
  615. } catch (Exception e) {
  616. e.printStackTrace();
  617. }
  618. return map;
  619. }
  620. @GetMapping("testGetUUID")
  621. public String testGetUUID() {
  622. return UUID.randomUUID().toString();
  623. }
  624. @GetMapping("testGetShortUUID")
  625. public String testGetShortUUID(Integer length) {
  626. // return UUID.randomUUID().toString()
  627. // .replace("-", "")
  628. // .substring(0, length);
  629. return IdUtil.simpleUUID().substring(0, length);
  630. }
  631. /**
  632. * BCrypt算法进行加密
  633. */
  634. @GetMapping("testPassword")
  635. public String testPassword(String value) {
  636. String password = Optional.ofNullable(value).orElse("123456");
  637. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  638. String encodedPassword = encoder.encode(password);
  639. boolean matched = encoder.matches(password, encodedPassword);
  640. return "Value: " + value + "\nencodedPassword: " + encodedPassword + "\nmatched: " + matched;
  641. }
  642. /**
  643. * 使用 MD5Util 工具类
  644. */
  645. @GetMapping("testMD5")
  646. public String testMD5(String value) throws NoSuchAlgorithmException {
  647. String password = Optional.ofNullable(value).orElse("123456");
  648. String version = "0.0.48";
  649. return "Value: " + value + "\n" +
  650. "MD5: " + MD5Util.encrypt(password) + "\n" +
  651. "Version: " + version;
  652. }
  653. @GetMapping("/testJSON")
  654. public String testJSON() throws JsonProcessingException {
  655. Integer[] a = MAPPER.readValue("1,2", Integer[].class);
  656. System.out.println("a: ");
  657. System.out.println(a);
  658. return "1";
  659. }
  660. @GetMapping("testFont")
  661. public String[] testFont() {
  662. GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  663. String[] fontNames = ge.getAvailableFontFamilyNames();
  664. for (String fontName : fontNames) {
  665. System.out.println(fontName);
  666. }
  667. return fontNames;
  668. }
  669. /**
  670. * Redisson 加锁
  671. * @return
  672. */
  673. @Lazy
  674. @Autowired
  675. RedissonClient redissonClient;
  676. @GetMapping("testRedisson")
  677. public String testGetRedisson() throws InterruptedException {
  678. RLock lock = redissonClient.getLock("my-lock");
  679. lock.tryLock(3, TimeUnit.SECONDS); // 阻塞式等待。默认加的锁是30s时间
  680. try {
  681. // 1、锁的自动续期,运行期间自动给锁续上新的30s,无需担心业务时间长,锁过期会自动被释放
  682. // 2、加锁的业务只要运行完成,就不会给当前锁续期,即使不手动释放锁,锁默认在30s后自动释放,避免死锁
  683. System.out.println("加锁成功,执行业务代码..."+Thread.currentThread().getId());
  684. Thread.sleep(3000);
  685. } catch (Exception e) {
  686. e.printStackTrace();
  687. } finally {
  688. System.out.println("释放锁..."+Thread.currentThread().getId());
  689. lock.unlock();
  690. }
  691. return "get lock!";
  692. }
  693. /**
  694. * Redisson 一般用于商品秒杀活动:
  695. */
  696. /*
  697. @Component
  698. public class DistributedLockExample {
  699. @Autowired
  700. private Redisson redisson;
  701. private RLock distributedLock;
  702. @PostConstruct
  703. private void init() {
  704. distributedLock = redisson.getLock("myDistributedLock");
  705. }
  706. public void performOperation() {
  707. try {
  708. // 尝试获取分布式锁,最多等待10秒
  709. boolean lockAcquired = distributedLock.tryLock(10, TimeUnit.SECONDS);
  710. if (lockAcquired) {
  711. // 获取锁成功,执行需要加锁的业务逻辑
  712. // ...
  713. } else {
  714. // 获取锁失败,处理异常情况
  715. // ...
  716. }
  717. } catch (InterruptedException e) {
  718. // 处理中断异常
  719. // ...
  720. } finally {
  721. // 释放分布式锁
  722. distributedLock.unlock();
  723. }
  724. }
  725. }
  726. */
  727. public static Object resource1 = new Object();
  728. public static Object resource2 = new Object();
  729. @GetMapping("testDeadLock")
  730. public String testDeadLock() {
  731. RLock lock = redissonClient.getLock("thread-lock");
  732. // 线程1
  733. new Thread(() -> {
  734. //System.out.println("------- lock thread-1 -------");
  735. lock.lock();
  736. synchronized (resource2) {
  737. System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
  738. try {
  739. Thread.sleep(3000);
  740. } catch (InterruptedException e) {
  741. throw new RuntimeException(e);
  742. }
  743. synchronized (resource1) {
  744. System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
  745. lock.unlock();
  746. }
  747. }
  748. }).start();
  749. // 线程2
  750. new Thread(() -> {
  751. //System.out.println("------- lock thread-2 -------");
  752. lock.lock();
  753. synchronized (resource1) {
  754. System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
  755. try {
  756. Thread.sleep(3000);
  757. } catch (InterruptedException e) {
  758. throw new RuntimeException(e);
  759. }
  760. synchronized (resource2) {
  761. System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
  762. lock.unlock();
  763. }
  764. }
  765. }).start();
  766. return "ok";
  767. }
  768. }