TestController.java 35 KB

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