微服务: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

相关文章

【区块链 + 人才服务】可信教育区块链治理系统 | FISCO BCOS应用案例

伴随着区块链技术的不断完善,其在教育信息化中的应用也在持续发展。利用区块链数据共识、不可篡改的特性, 将与教育相关的数据要素在区块链上进行存证确权,在确保数据可信的前提下,促进教育的公平、透明、开放,为教育教学质量提升赋能,实现教育数据的安全共享、高等教育体系的智慧治理。 可信教育区块链治理系统的顶层治理架构由教育部、高校、企业、学生等多方角色共同参与建设、维护,支撑教育资源共享、教学质量评估、

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

基于SpringBoot的宠物服务系统+uniapp小程序+LW参考示例

系列文章目录 1.基于SSM的洗衣房管理系统+原生微信小程序+LW参考示例 2.基于SpringBoot的宠物摄影网站管理系统+LW参考示例 3.基于SpringBoot+Vue的企业人事管理系统+LW参考示例 4.基于SSM的高校实验室管理系统+LW参考示例 5.基于SpringBoot的二手数码回收系统+原生微信小程序+LW参考示例 6.基于SSM的民宿预订管理系统+LW参考示例 7.基于

Golang支持平滑升级的HTTP服务

前段时间用Golang在做一个HTTP的接口,因编译型语言的特性,修改了代码需要重新编译可执行文件,关闭正在运行的老程序,并启动新程序。对于访问量较大的面向用户的产品,关闭、重启的过程中势必会出现无法访问的情况,从而影响用户体验。 使用Golang的系统包开发HTTP服务,是无法支持平滑升级(优雅重启)的,本文将探讨如何解决该问题。 一、平滑升级(优雅重启)的一般思路 一般情况下,要实现平滑

Golang服务平滑重启

与重载配置相同的是我们也需要通过信号来通知server重启,但关键在于平滑重启,如果只是简单的重启,只需要kill掉,然后再拉起即可。平滑重启意味着server升级的时候可以不用停止业务。 我们先来看下Github上有没有相应的库解决这个问题,然后找到了如下三个库: facebookgo/grace - Graceful restart & zero downtime deploy for G

Java后端微服务架构下的API限流策略:Guava RateLimiter

Java后端微服务架构下的API限流策略:Guava RateLimiter 大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿! 在微服务架构中,API限流是保护服务不受过度使用和拒绝服务攻击的重要手段。Guava RateLimiter是Google开源的Java库中的一个组件,提供了简单易用的限流功能。 API限流概述 API限流通过控制请求的速率来防止

【微服务】Ribbon(负载均衡,服务调用)+ OpenFeign(服务发现,远程调用)【详解】

文章目录 1.Ribbon(负载均衡,服务调用)1.1问题引出1.2 Ribbon负载均衡1.3 RestTemplate整合Ribbon1.4 指定Ribbon负载均衡策略1.4.1 配置文件1.4.2 配置类1.4.3 定义Ribbon客户端配置1.4.4 自定义负载均衡策略 2.OpenFeign面向接口的服务调用(服务发现,远程调用)2.1 OpenFeign的使用2.1 .1创建

java后端服务监控与告警:Prometheus与Grafana集成

Java后端服务监控与告警:Prometheus与Grafana集成 大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿! 在现代的微服务架构中,监控和告警是确保服务稳定性的关键组成部分。Prometheus和Grafana是两个强大的工具,它们可以集成在一起,为Java后端服务提供实时监控和可视化告警。 服务监控的重要性 服务监控可以帮助我们实时了解服务的健

OpenStack离线Train版安装系列—3控制节点-Keystone认证服务组件

本系列文章包含从OpenStack离线源制作到完成OpenStack安装的全部过程。 在本系列教程中使用的OpenStack的安装版本为第20个版本Train(简称T版本),2020年5月13日,OpenStack社区发布了第21个版本Ussuri(简称U版本)。 OpenStack部署系列文章 OpenStack Victoria版 安装部署系列教程 OpenStack Ussuri版

OpenStack离线Train版安装系列—10.控制节点-Heat服务组件

本系列文章包含从OpenStack离线源制作到完成OpenStack安装的全部过程。 在本系列教程中使用的OpenStack的安装版本为第20个版本Train(简称T版本),2020年5月13日,OpenStack社区发布了第21个版本Ussuri(简称U版本)。 OpenStack部署系列文章 OpenStack Victoria版 安装部署系列教程 OpenStack Ussuri版