TestController.java 34 KB

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