TestController.java 39 KB

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