微服务:Bot代码执行

2024-03-17 01:28
文章标签 服务 代码执行 bot

本文主要是介绍微服务:Bot代码执行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

每次要多传一个bot_id 

判网关的时候判127.0.0.1所以最好改localhost

创建SpringCloud的子项目 BotRunningSystem
在BotRunningSystem项目中添加依赖:
joor-java-8

可动态编译Java代码
2. 修改前端,传入对Bot的选择操作

package com.kob.botrunningsystem.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate getRestTemplate() {return new RestTemplate();}
}
package com.kob.botrunningsystem.config;import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers("/bot/add/").hasIpAddress("127.0.0.1").antMatchers(HttpMethod.OPTIONS).permitAll().anyRequest().authenticated();}
}
package com.kob.botrunningsystem.controller;import com.kob.botrunningsystem.service.BotRunningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.Objects;@RestController
public class BotRunningController {@Autowiredprivate BotRunningService botRunningService;@PostMapping("/bot/add/")public String addBot(@RequestParam MultiValueMap<String, String> data) {Integer userId = Integer.parseInt(Objects.requireNonNull(data.getFirst("user_id")));String botCode = data.getFirst("bot_code");String input = data.getFirst("input");return botRunningService.addBot(userId, botCode, input);}
}
package com.kob.botrunningsystem.service.impl.utils;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Bot {Integer userId;String botCode;String input;
}

        

 

package com.kob.botrunningsystem.service.impl.utils;import com.kob.botrunningsystem.utils.BotInterface;
import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;import java.util.UUID;@Component
public class Consumer extends Thread {private Bot bot;private static RestTemplate restTemplate;private final static String receiveBotMoveUrl = "http://127.0.0.1:8080/pk/receive/bot/move/";@Autowiredpublic void setRestTemplate(RestTemplate restTemplate) {Consumer.restTemplate = restTemplate;}public void startTimeout(long timeout, Bot bot) {this.bot = bot;this.start();try {this.join(timeout);  // 最多等待timeout秒} catch (InterruptedException e) {e.printStackTrace();} finally {this.interrupt();  // 终端当前线程}}private String addUid(String code, String uid) {  // 在code中的Bot类名后添加uidint k = code.indexOf(" implements com.kob.botrunningsystem.utils.BotInterface");return code.substring(0, k) + uid + code.substring(k);}@Overridepublic void run() {UUID uuid = UUID.randomUUID();String uid = uuid.toString().substring(0, 8);BotInterface botInterface = Reflect.compile("com.kob.botrunningsystem.utils.Bot" + uid,addUid(bot.getBotCode(), uid)).create().get();Integer direction = botInterface.nextMove(bot.getInput());System.out.println("move-direction: " + bot.getUserId() + " " + direction);MultiValueMap<String, String> data = new LinkedMultiValueMap<>();data.add("user_id", bot.getUserId().toString());data.add("direction", direction.toString());restTemplate.postForObject(receiveBotMoveUrl, data, String.class);}
}
package com.kob.botrunningsystem.service.impl;import com.kob.botrunningsystem.service.BotRunningService;
import com.kob.botrunningsystem.service.impl.utils.BotPool;
import org.springframework.stereotype.Service;@Service
public class BotRunningServiceImpl implements BotRunningService {public final static BotPool botPool = new BotPool();@Overridepublic String addBot(Integer userId, String botCode, String input) {System.out.println("add bot: " + userId + " " + botCode + " " + input);botPool.addBot(userId, botCode, input);return "add bot success";}
}

 

package com.kob.botrunningsystem.service;public interface BotRunningService {String addBot(Integer userId, String botCode, String input);
}

 

package com.kob.botrunningsystem.utils;import java.util.ArrayList;
import java.util.List;public class Bot implements com.kob.botrunningsystem.utils.BotInterface {static class Cell {public int x, y;public Cell(int x, int y) {this.x = x;this.y = y;}}private boolean check_tail_increasing(int step) {  // 检验当前回合,蛇的长度是否增加if (step <= 10) return true;return step % 3 == 1;}public List<Cell> getCells(int sx, int sy, String steps) {steps = steps.substring(1, steps.length() - 1);List<Cell> res = new ArrayList<>();int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};int x = sx, y = sy;int step = 0;res.add(new Cell(x, y));for (int i = 0; i < steps.length(); i ++ ) {int d = steps.charAt(i) - '0';x += dx[d];y += dy[d];res.add(new Cell(x, y));if (!check_tail_increasing( ++ step)) {res.remove(0);}}return res;}@Overridepublic Integer nextMove(String input) {String[] strs = input.split("#");int[][] g = new int[15][16];for (int i = 0, k = 0; i < 15; i ++ ) {for (int j = 0; j < 16; j ++, k ++ ) {if (strs[0].charAt(k) == '1') {g[i][j] = 1;}}}int aSx = Integer.parseInt(strs[1]), aSy = Integer.parseInt(strs[2]);int bSx = Integer.parseInt(strs[4]), bSy = Integer.parseInt(strs[5]);List<Cell> aCells = getCells(aSx, aSy, strs[3]);List<Cell> bCells = getCells(bSx, bSy, strs[6]);for (Cell c: aCells) g[c.x][c.y] = 1;for (Cell c: bCells) g[c.x][c.y] = 1;int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};for (int i = 0; i < 4; i ++ ) {int x = aCells.get(aCells.size() - 1).x + dx[i];int y = aCells.get(aCells.size() - 1).y + dy[i];if (x >= 0 && x < 15 && y >= 0 && y < 16 && g[x][y] == 0) {return i;}}return 0;}
}

 

package com.kob.botrunningsystem.utils;public interface BotInterface {Integer nextMove(String input);
}

 

package com.kob.botrunningsystem;import com.kob.botrunningsystem.service.impl.BotRunningServiceImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class BotRunningSystemApplication {public static void main(String[] args) {BotRunningServiceImpl.botPool.start();SpringApplication.run(BotRunningSystemApplication.class, args);}
}

终极流程

这篇关于微服务:Bot代码执行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/817374

相关文章

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Linux上设置Ollama服务配置(常用环境变量)

《Linux上设置Ollama服务配置(常用环境变量)》本文主要介绍了Linux上设置Ollama服务配置(常用环境变量),Ollama提供了多种环境变量供配置,如调试模式、模型目录等,下面就来介绍一... 目录在 linux 上设置环境变量配置 OllamPOgxSRJfa手动安装安装特定版本查看日志在

SpringCloud之LoadBalancer负载均衡服务调用过程

《SpringCloud之LoadBalancer负载均衡服务调用过程》:本文主要介绍SpringCloud之LoadBalancer负载均衡服务调用过程,具有很好的参考价值,希望对大家有所帮助,... 目录前言一、LoadBalancer是什么?二、使用步骤1、启动consul2、客户端加入依赖3、以服务

Nginx配置系统服务&设置环境变量方式

《Nginx配置系统服务&设置环境变量方式》本文介绍了如何将Nginx配置为系统服务并设置环境变量,以便更方便地对Nginx进行操作,通过配置系统服务,可以使用系统命令来启动、停止或重新加载Nginx... 目录1.Nginx操作问题2.配置系统服android务3.设置环境变量总结1.Nginx操作问题

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

TP-Link PDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务

《TP-LinkPDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务》近期,路由器制造巨头普联(TP-Link)在用户群体中引发了一系列重要变动,上个月,公司发出了一则通知,明确要求所... 路由器厂商普联(TP-Link)上个月发布公告要求所有用户必须完成实名认证后才能继续使用普联提供的 D

微服务架构之使用RabbitMQ进行异步处理方式

《微服务架构之使用RabbitMQ进行异步处理方式》本文介绍了RabbitMQ的基本概念、异步调用处理逻辑、RabbitMQ的基本使用方法以及在SpringBoot项目中使用RabbitMQ解决高并发... 目录一.什么是RabbitMQ?二.异步调用处理逻辑:三.RabbitMQ的基本使用1.安装2.架构

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

windos server2022的配置故障转移服务的图文教程

《windosserver2022的配置故障转移服务的图文教程》本文主要介绍了windosserver2022的配置故障转移服务的图文教程,以确保服务和应用程序的连续性和可用性,文中通过图文介绍的非... 目录准备环境:步骤故障转移群集是 Windows Server 2022 中提供的一种功能,用于在多个