TestController.java 38 KB

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