设备对接,及 单点登录
This commit is contained in:
parent
be99d7e3e0
commit
ab4b621ad7
|
@ -48,6 +48,13 @@
|
|||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>4.1.63.Final</version>
|
||||
</dependency>
|
||||
|
||||
<!-- SpringBoot 测试 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -80,6 +87,14 @@
|
|||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- forest 继承-->
|
||||
<dependency>
|
||||
<groupId>com.dtflys.forest</groupId>
|
||||
<artifactId>forest-spring-boot-starter</artifactId>
|
||||
<version>1.5.36</version>
|
||||
</dependency>
|
||||
|
||||
<!-- redis 缓存操作 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package com.ruoyi;
|
||||
|
||||
import com.ruoyi.common.tcp.CarTcpNettyServer;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
|
@ -16,6 +17,11 @@ public class RuoYiApplication
|
|||
{
|
||||
// System.setProperty("spring.devtools.restart.enabled", "false");
|
||||
SpringApplication.run(RuoYiApplication.class, args);
|
||||
try {
|
||||
new CarTcpNettyServer().bind(8001);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +
|
||||
" .-------. ____ __ \n" +
|
||||
" | _ _ \\ \\ \\ / / \n" +
|
||||
|
|
|
@ -0,0 +1,209 @@
|
|||
package com.ruoyi.common.OAuth;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
/**
|
||||
* Author:Zhenggang
|
||||
* CreateTime:2018/10/30 18:22
|
||||
*/
|
||||
@Controller
|
||||
public class OauthDemo {
|
||||
|
||||
/**
|
||||
* 认证地址、应用注册id、应用注册key 三个参数因环境不同而不同,建议改为从配置文件中读取
|
||||
*/
|
||||
//认证地址
|
||||
public static final String BASE_URL = "http://utuum.sd-gold.com:7021/idp/oauth2";
|
||||
//应用注册id
|
||||
public static final String CLIENT_ID = "ERM";
|
||||
//应用注册key
|
||||
public static final String CLIENT_SECRET = "ermsecret";
|
||||
|
||||
//获取access_token的url
|
||||
public static final String GET_ACCESS_TOKEN_URL = BASE_URL + "/getToken";
|
||||
//获取用户信息的url
|
||||
public static final String GET_USERINFO_URL = BASE_URL + "/getUserInfo?client_id=" + CLIENT_ID + "&access_token=";
|
||||
|
||||
|
||||
/**
|
||||
* 访问ip:port/root/redirectToAuth时,拼接并且重定向到
|
||||
* http://utuum.sd-gold.com:7021/idp/oauth2/authorize?redirect_uri=ip:port/root/getAccountName&state=sso&client_id=ECD&response_type=code
|
||||
*/
|
||||
@RequestMapping("/redirectToAuth")
|
||||
public void reToAuth(HttpServletRequest request, HttpServletResponse response) {
|
||||
String url = request.getRequestURL().toString().replaceAll("/redirectToAuth", "/getAccountName");
|
||||
String re_url = BASE_URL + "/authorize?redirect_uri=" + url + "&state=sso&client_id=" + CLIENT_ID + "&response_type=code";
|
||||
try {
|
||||
response.sendRedirect(re_url);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 此方法最后取到账号acc的值后,需要各系统进行登录逻辑处理
|
||||
* @param code 用户名和密码认证通过后返回的code,access_token,从而获取到用户或账号信息
|
||||
* @return
|
||||
*/
|
||||
@ResponseBody
|
||||
@RequestMapping(value = "/getAccountName", method = RequestMethod.GET)
|
||||
public String getAccountName(@RequestParam(name = "code") String code) {
|
||||
String accessTokenParam = null;
|
||||
System.out.println("1).authorize code is:" + code);
|
||||
try {
|
||||
accessTokenParam = "client_id=" + URLEncoder.encode(this.CLIENT_ID, "UTF-8");
|
||||
accessTokenParam += "&client_secret=" + URLEncoder.encode(this.CLIENT_SECRET, "UTF-8");
|
||||
accessTokenParam += "&grant_type=" + URLEncoder.encode("authorization_code", "UTF-8");
|
||||
accessTokenParam += "&code=" + URLEncoder.encode(code, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String TokenString = getStringPost(this.GET_ACCESS_TOKEN_URL, accessTokenParam);
|
||||
|
||||
if (TokenString == null || TokenString.equals("")) {
|
||||
System.out.println("cannot get tokenInfo");
|
||||
return null;
|
||||
}
|
||||
System.out.println("2).tokenInfo is: " + TokenString);
|
||||
String accessToken = getValueFromJson(TokenString, "access_token");
|
||||
String addressParam = this.GET_USERINFO_URL + accessToken;
|
||||
String userInfo = getStringGet(addressParam);
|
||||
if (userInfo == null || userInfo.equals("")) {
|
||||
System.out.println("cannot get userInfo");
|
||||
return null;
|
||||
}
|
||||
System.out.println("3).userInfo is :" + userInfo);
|
||||
String acc = getValueFromJson(userInfo, "spRoleList");
|
||||
if (acc == null || acc.equals("")) {
|
||||
System.out.println("cannot get acc");
|
||||
return null;
|
||||
}
|
||||
System.out.println("the acc is :" + acc);
|
||||
return "the acc is : " + acc;
|
||||
}
|
||||
|
||||
|
||||
public String getStringPost(String address, String content) {
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
DataOutputStream out = null;
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
URL url = new URL(address);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setConnectTimeout(20000);//设置超时时间
|
||||
conn.setDoOutput(true);//设置连接是否可输出数据
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setUseCaches(false);
|
||||
conn.setInstanceFollowRedirects(true);
|
||||
|
||||
conn.connect();
|
||||
out = new DataOutputStream(conn.getOutputStream());
|
||||
|
||||
out.writeBytes(content);
|
||||
out.flush();
|
||||
out.close();
|
||||
System.out.println("返回代码:" + conn.getResponseCode());
|
||||
if (conn.getResponseCode() == 200) {
|
||||
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
||||
String line = "";
|
||||
while ((line = reader.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
reader.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
|
||||
if (out != null) {
|
||||
try {
|
||||
out.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (reader != null) {
|
||||
try {
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public String getStringGet(String address) {
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
URL url = new URL(address);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.connect();
|
||||
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
||||
String line = "";
|
||||
while ((line = reader.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
reader.close();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (reader != null) {
|
||||
try {
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @param jsonString json字符串
|
||||
* @param key 键值
|
||||
* 此处解析json依赖jackson,可改为fastjson、gosn等
|
||||
* @return
|
||||
*/
|
||||
public String getValueFromJson(String jsonString, String key) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String value = "";
|
||||
try {
|
||||
JsonNode rootNode = mapper.readTree(jsonString);
|
||||
JsonNode tempValue = rootNode.get(key);
|
||||
if (tempValue == null) {
|
||||
return value;
|
||||
}
|
||||
if (tempValue.isArray()) {
|
||||
if (tempValue.size() > 0) {
|
||||
value = tempValue.get(0).asText();
|
||||
}
|
||||
} else {
|
||||
value = tempValue.asText();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
package com.ruoyi.common.OAuth;
|
||||
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Author:Zhenggang
|
||||
* CreateTime:2018/11/21 13:49
|
||||
*/
|
||||
@Controller
|
||||
public class RestDemo {
|
||||
|
||||
/**
|
||||
* REST_BASE_URL、APP_ID参数建议改为可配置项
|
||||
*/
|
||||
public static final String REST_BASE_URL = "http://utuum.sd-gold.com:7021/idp/restful";
|
||||
public static final String APP_ID = "COP";
|
||||
|
||||
/**
|
||||
* 方法得到accountName后,需要各个系统处理登录逻辑
|
||||
* @param username
|
||||
* @param password
|
||||
* @param httpRequest
|
||||
* @return
|
||||
*/
|
||||
@ResponseBody
|
||||
@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
|
||||
public Map<String, Object> login(@RequestParam(name = "username") String username,
|
||||
@RequestParam(name = "password") String password,
|
||||
HttpServletRequest httpRequest) {
|
||||
String authorizeParam = null;
|
||||
Map<String, Object> resultMap = new HashMap<>();
|
||||
resultMap.put("success", false);
|
||||
String remoteIp = "";
|
||||
remoteIp = getRemotIpAddr(httpRequest);
|
||||
// remoteIp = "10.8.41.156";
|
||||
System.out.println("remoteIp is:" + remoteIp);
|
||||
|
||||
String error = null;
|
||||
//认证用户,通过后得到tokenId
|
||||
authorizeParam = "appId=" + APP_ID + "&userName=" + username + "&password=" + password + "&remoteIp=" + remoteIp;
|
||||
String tokenJson = getStringGet(REST_BASE_URL + "/IDPAuthenticate?" + authorizeParam);
|
||||
|
||||
JSONObject tokenJsonObject = JSONObject.parseObject(tokenJson).getJSONObject("data");
|
||||
if (tokenJsonObject == null) {
|
||||
error = JSONObject.parseObject(tokenJson).getJSONObject("message").toString();
|
||||
System.out.println(error);
|
||||
resultMap.put("error", error);
|
||||
return resultMap;
|
||||
}
|
||||
String tokenId = "";
|
||||
if (tokenJsonObject.containsKey("tokenId")) {
|
||||
tokenId = tokenJsonObject.getString("tokenId");
|
||||
}
|
||||
System.out.println("1.----tokenid is-----:" + tokenId);
|
||||
//利用tokenId获取用户信息
|
||||
String userInfoParam = "appId=" + APP_ID + "&tokenId=" + tokenId + "&remoteIp=" + remoteIp;
|
||||
String userInfoString = getStringGet(REST_BASE_URL + "/getIDPUserAttributes?" + userInfoParam);
|
||||
JSONObject userInfoError = JSONObject.parseObject(userInfoString).getJSONObject("message");
|
||||
if (userInfoError != null && userInfoError.size() > 0) {
|
||||
error = userInfoError.toString();
|
||||
resultMap.put("error", error);
|
||||
return resultMap;
|
||||
}
|
||||
JSONObject userInfoJson = JSONObject.parseObject(userInfoString).getJSONObject("data");
|
||||
System.out.println("2.----userinfo is------:" + userInfoJson);
|
||||
JSONArray accountList = userInfoJson.getJSONObject("attributes").getJSONArray("spRoleList");
|
||||
if (accountList.size() == 0) {
|
||||
error = "account not exist";
|
||||
resultMap.put("error", error);
|
||||
return resultMap;
|
||||
}
|
||||
// String accountName = accountList.get(0);
|
||||
System.out.println("3.----username is-------- : " + "accountName");
|
||||
|
||||
resultMap.put("success", true);
|
||||
resultMap.put("accessToken", tokenId);
|
||||
resultMap.put("accountList", accountList);
|
||||
resultMap.put("remoteIp", remoteIp);
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
|
||||
public String getStringGet(String address) {
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
BufferedReader reader = null;
|
||||
try {
|
||||
URL url = new URL(address);
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.connect();
|
||||
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
|
||||
String line = "";
|
||||
while ((line = reader.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
reader.close();
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (reader != null) {
|
||||
try {
|
||||
reader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String getRemotIpAddr(HttpServletRequest request) {
|
||||
String ip = request.getHeader("x-forwarded-for");
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.ruoyi.common.sms.forest;
|
||||
|
||||
import com.dtflys.forest.annotation.Get;
|
||||
import com.dtflys.forest.annotation.Request;
|
||||
|
||||
public interface MyClient {
|
||||
|
||||
@Get("http://localhost:8080/hello")
|
||||
String simpleRequest();
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.ruoyi.common.sms;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.webservices.client.WebServiceTemplateBuilder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.net.HttpURLConnection;
|
||||
|
||||
@Component
|
||||
public class sms {
|
||||
|
||||
|
||||
// @Autowired
|
||||
// private WebServiceTemplateBuilder webServiceTemplateBuilder;
|
||||
public void sms(String phones,String msg){
|
||||
// HttpURLConnection
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.ruoyi.common.task;
|
||||
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.ruoyi.common.task.forest.MyTaskClient;
|
||||
import com.ruoyi.common.utils.sign.Md5Utils;
|
||||
import com.ruoyi.project.oil.domain.monitor.ThDevice;
|
||||
import com.ruoyi.project.outside.service.OutSideService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
@Component
|
||||
public class EquTask {
|
||||
|
||||
|
||||
|
||||
@Autowired
|
||||
private MyTaskClient myClient;
|
||||
@Autowired
|
||||
private OutSideService outSideService;
|
||||
/**
|
||||
* 港口原有设备对接
|
||||
*/
|
||||
public void equ(){
|
||||
String tokenByStr = myClient.loginRequest("admin", Md5Utils.hash("123456"));
|
||||
JSONObject tokenByJson = JSONObject.parseObject(tokenByStr);
|
||||
JSONObject dataByJson = tokenByJson.getJSONObject("data");
|
||||
String token = dataByJson.getString("token");
|
||||
ArrayList<ThDevice> equLists = new ArrayList<>(); //查询 数据库 获取 港口以前的 设备信息
|
||||
equLists.forEach(e->{
|
||||
String vocByStr = myClient.selectRequest(token, e.getSn(), e.getName());
|
||||
JSONObject vocByJson = JSONObject.parseObject(vocByStr);
|
||||
JSONObject vocDataByJson = vocByJson.getJSONObject("data");
|
||||
JSONArray vocByArray = vocDataByJson.getJSONArray("array");
|
||||
|
||||
});
|
||||
}
|
||||
public void dateByDay(){
|
||||
outSideService.monthTask("");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.ruoyi.common.task.forest;
|
||||
|
||||
import com.dtflys.forest.annotation.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public interface MyTaskClient {
|
||||
|
||||
@Post(url = "http://10.201.35.30:8090/user/login",
|
||||
headers = {
|
||||
"Content-Type: application/json"
|
||||
}
|
||||
)
|
||||
String loginRequest(@Body String userName,@Body String password);
|
||||
@Get(url = "http://10.201.35.30:8090/enviSensor/select?page=1&pageSize=20&valid=0&type=5&sensorUId={sensorUId}&label={label}"
|
||||
)
|
||||
String selectRequest(@Body String token,@Var("sensorUId") String sensorUId,@Var("label")String label);
|
||||
|
||||
}
|
|
@ -0,0 +1,129 @@
|
|||
package com.ruoyi.common.tcp;
|
||||
|
||||
import com.ruoyi.common.utils.spring.SpringUtils;
|
||||
import com.ruoyi.project.outside.service.OutSideService;
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||
import io.netty.util.CharsetUtil;
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
/**
|
||||
* I/O数据读写处理类
|
||||
*
|
||||
* @author xiaobo
|
||||
*/
|
||||
|
||||
public class CarTcpNettyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {
|
||||
/**
|
||||
* 从客户端收到新的数据时,这个方法会在收到消息时被调用
|
||||
*
|
||||
* @param ctx
|
||||
* @param msg
|
||||
*/
|
||||
@Override
|
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception, IOException {
|
||||
// 这里是在前面的DelimiterBasedFrameDecoder转为了ByteBuf,验证是否是ByteBuf
|
||||
if (msg instanceof ByteBuf) {
|
||||
ByteBuf byteBuf = (ByteBuf) msg;
|
||||
try {
|
||||
String receivedData = byteBuf.toString(CharsetUtil.UTF_8);
|
||||
// 接收完整数据
|
||||
handleReceivedData(receivedData);
|
||||
} finally {
|
||||
// 释放 ByteBuf 占用的资源
|
||||
byteBuf.release();
|
||||
// 回复消息
|
||||
ctx.writeAndFlush(Unpooled.copiedBuffer("收到over", CharsetUtil.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
private void handleReceivedData(String receivedData) {
|
||||
// 数据处理 tudo 数据 存入
|
||||
OutSideService outSideService = SpringUtils.getBean(OutSideService.class);
|
||||
outSideService.insertDevice(receivedData);
|
||||
// 这里如果想实现spring中bean的注入,可以用geBean的方式获取
|
||||
System.out.println(receivedData);
|
||||
}
|
||||
/**
|
||||
* 从客户端收到新的数据、读取完成时调用
|
||||
*
|
||||
* @param ctx
|
||||
*/
|
||||
@Override
|
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws IOException {
|
||||
// log.info("channelReadComplete");
|
||||
ctx.flush();
|
||||
}
|
||||
/**
|
||||
* 当出现 Throwable 对象才会被调用,即当 Netty 由于 IO 错误或者处理器在处理事件时抛出的异常时
|
||||
*
|
||||
* @param ctx
|
||||
* @param cause
|
||||
*/
|
||||
@Override
|
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws IOException {
|
||||
cause.printStackTrace();
|
||||
ctx.close();// 抛出异常,断开与客户端的连接
|
||||
}
|
||||
/**
|
||||
* 客户端与服务端第一次建立连接时 执行
|
||||
*
|
||||
* @param ctx
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException {
|
||||
super.channelActive(ctx);
|
||||
ctx.channel().read();
|
||||
InetSocketAddress socket = (InetSocketAddress) ctx.channel().remoteAddress();
|
||||
String clientIp = socket.getAddress().getHostAddress();
|
||||
// 此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
|
||||
System.out.println("channelActive:" + clientIp + ctx.name());
|
||||
// 这里是向客户端发送回应
|
||||
ctx.writeAndFlush(Unpooled.copiedBuffer("收到over", CharsetUtil.UTF_8));
|
||||
}
|
||||
/**
|
||||
* 客户端与服务端 断连时 执行
|
||||
*
|
||||
* @param ctx
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException {
|
||||
super.channelInactive(ctx);
|
||||
InetSocketAddress socket = (InetSocketAddress) ctx.channel().remoteAddress();
|
||||
String clientIp = socket.getAddress().getHostAddress();
|
||||
// 断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
|
||||
ctx.close();
|
||||
// log.info("channelInactive:{}", clientIp);
|
||||
}
|
||||
/**
|
||||
* 服务端当read超时, 会调用这个方法
|
||||
*
|
||||
* @param ctx
|
||||
* @param evt
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception, IOException {
|
||||
super.userEventTriggered(ctx, evt);
|
||||
InetSocketAddress socket = (InetSocketAddress) ctx.channel().remoteAddress();
|
||||
String clientIp = socket.getAddress().getHostAddress();
|
||||
ctx.close();// 超时时断开连接
|
||||
// log.info("userEventTriggered:" + clientIp);
|
||||
}
|
||||
@Override
|
||||
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
|
||||
// log.info("channelRegistered");
|
||||
}
|
||||
@Override
|
||||
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
|
||||
// log.info("channelUnregistered");
|
||||
}
|
||||
@Override
|
||||
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
|
||||
// log.info("channelWritabilityChanged");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.ruoyi.common.tcp;
|
||||
|
||||
import io.netty.buffer.ByteBuf;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
|
||||
/**
|
||||
* description: <h1>通道初始化</h1>
|
||||
*
|
||||
* @author bo
|
||||
* @version 1.0
|
||||
* @date 2024/2/27 16:13
|
||||
*/
|
||||
public class CarTcpNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {
|
||||
@Override
|
||||
protected void initChannel(Channel ch) throws Exception {
|
||||
ByteBuf delemiter = Unpooled.buffer();
|
||||
delemiter.writeBytes("$".getBytes());
|
||||
// 这里就是解决数据过长问题,而且数据是以$结尾的
|
||||
ch.pipeline().addLast(new DelimiterBasedFrameDecoder(907200, true, true, delemiter));
|
||||
// 自定义ChannelInboundHandlerAdapter
|
||||
ch.pipeline().addLast(new CarTcpNettyChannelInboundHandlerAdapter());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.ruoyi.common.tcp;
|
||||
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.AdaptiveRecvByteBufAllocator;
|
||||
import io.netty.channel.ChannelFuture;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
/**
|
||||
* description: <h1>netty创建的TCP</h1>
|
||||
*
|
||||
* @author bo
|
||||
* @version 1.0
|
||||
* @date 2024/2/27 16:25
|
||||
*/
|
||||
public class CarTcpNettyServer {
|
||||
public void bind(int port) throws Exception {
|
||||
// 配置服务端的NIO线程组
|
||||
// NioEventLoopGroup 是用来处理I/O操作的Reactor线程组
|
||||
// bossGroup:用来接收进来的连接,workerGroup:用来处理已经被接收的连接,进行socketChannel的网络读写,
|
||||
// bossGroup接收到连接后就会把连接信息注册到workerGroup
|
||||
// workerGroup的EventLoopGroup默认的线程数是CPU核数的二倍
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup();
|
||||
try {
|
||||
ServerBootstrap serverBootstrap = new ServerBootstrap();
|
||||
serverBootstrap.group(bossGroup, workerGroup)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
// netty 默认数据包传输大小为1024字节, 设置它可以自动调整下一次缓冲区建立时分配的空间大小,避免内存的浪费 最小 初始化 最大 (根据生产环境实际情况来定)
|
||||
// 使用对象池,重用缓冲区
|
||||
.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576))
|
||||
.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(64, 10496, 1048576))
|
||||
// 设置 I/O处理类,主要用于网络I/O事件,记录日志,编码、解码消息
|
||||
.childHandler(new CarTcpNettyChannelInitializer<SocketChannel>());
|
||||
// log.info("<===========netty server start success!==============>");
|
||||
// 绑定端口,同步等待成功
|
||||
ChannelFuture f = serverBootstrap.bind(port).sync();
|
||||
// 等待服务器监听端口关闭
|
||||
f.channel().closeFuture().sync();
|
||||
} finally {
|
||||
// 退出,释放线程池资源
|
||||
bossGroup.shutdownGracefully();
|
||||
workerGroup.shutdownGracefully();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -39,5 +39,6 @@ public class OutSideController extends BaseController {
|
|||
//
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,268 @@
|
|||
package com.ruoyi.project.system.controller;
|
||||
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.banboocloud.Codec.BamboocloudFacade;
|
||||
import com.ruoyi.common.utils.reflect.ReflectUtils;
|
||||
import com.ruoyi.framework.web.controller.BaseController;
|
||||
import com.ruoyi.project.system.domain.SysUser;
|
||||
import com.ruoyi.project.system.service.ISysDeptService;
|
||||
import com.ruoyi.project.system.service.ISysPostService;
|
||||
import com.ruoyi.project.system.service.ISysRoleService;
|
||||
import com.ruoyi.project.system.service.ISysUserService;
|
||||
import com.ruoyi.project.system.utils.BamboocloudUtils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* swagger 用户测试方法
|
||||
* 加密认证
|
||||
* @author ruoyi
|
||||
*/
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/bbc/user")
|
||||
public class BbcController extends BaseController {
|
||||
|
||||
private String bimRequestId;
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
|
||||
|
||||
|
||||
@Autowired
|
||||
private ISysUserService userService;
|
||||
|
||||
@Autowired
|
||||
private ISysRoleService roleService;
|
||||
|
||||
@Autowired
|
||||
private ISysDeptService deptService;
|
||||
|
||||
@Autowired
|
||||
private ISysPostService postService;
|
||||
|
||||
// @ApiOperation("测试")
|
||||
@RequestMapping()
|
||||
public JSONObject bbcUser() {
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
jsonObject.put("resultCode", "0");
|
||||
jsonObject.put("message", "success");
|
||||
return jsonObject;
|
||||
|
||||
}
|
||||
|
||||
// @ApiOperation("对象属性字段查询")
|
||||
@PostMapping("/schemaService")
|
||||
public String SchemaService(HttpServletRequest req, HttpServletResponse resp) {
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
|
||||
// StringBuilder sb = stringBuilder(req);
|
||||
String bodyparam= BamboocloudUtils.getRequestBody(req);
|
||||
logger.info("json--param-->" + bodyparam);
|
||||
// String bodyparam = sb.toString();
|
||||
//解密json字符传
|
||||
bodyparam = BamboocloudUtils.getPlaintext(bodyparam, "123456", "AES");
|
||||
logger.info("json--param-->" + bodyparam);
|
||||
Map<String, Object> reqmap = (Map<String, Object>) JSON.parse(bodyparam);
|
||||
//验证签名
|
||||
if (BamboocloudUtils.verify(reqmap, "MD5").booleanValue()) {
|
||||
String username = (String) reqmap.get("bimRemoteUser");
|
||||
String password = (String) reqmap.get("bimRemotePwd");
|
||||
//判断接口中的调用名及调用密码是否正确
|
||||
if (BamboocloudUtils.checkUsernamePassword(username, password)) {
|
||||
// //添加返回的对象及属性字段名
|
||||
// MapJson mapJson = new MapJson();
|
||||
// Map<String, List<Map<String, Object>>> map = new HashMap<>();
|
||||
// jsonObject.put("account", mapJson.accountList());
|
||||
// jsonObject.put("organization", mapJson.organizationList());
|
||||
// jsonObject.put("role", mapJson.roleList());
|
||||
// jsonObject.put("post", mapJson.postList());
|
||||
// jsonObject.put("dict", mapJson.dictDataList());
|
||||
// jsonObject.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
String mapJs = JSON.toJSONString(jsonObject);
|
||||
logger.info(jsonObject.toJSONString());
|
||||
//返回加密的json字符串
|
||||
mapJs = BamboocloudFacade.encrypt(mapJs, "123456", "AES");
|
||||
//jsonObject.put(map);
|
||||
//<Object> values = jsonObject.values();
|
||||
return mapJs;
|
||||
}
|
||||
}
|
||||
jsonObject.put("bimRequestId", bimRequestId);
|
||||
jsonObject.put("resultCode", "505");
|
||||
jsonObject.put("message", "连接失败,请检查连接器配置的参数");
|
||||
logger.info(jsonObject.toJSONString());
|
||||
String mapJs = JSON.toJSONString(jsonObject);
|
||||
//返回加密的json字符串
|
||||
mapJs = BamboocloudFacade.encrypt(mapJs, "123456", "AES");
|
||||
return mapJs;
|
||||
}
|
||||
|
||||
// @ApiOperation("新增用户")
|
||||
// @ApiImplicitParam(name = "user", value = "新增用户信息", dataType = "User")
|
||||
@PostMapping("/UserCreateService")
|
||||
@ResponseBody
|
||||
public String userCreateService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
|
||||
Map<String, Object> schema = new HashMap<String, Object>();
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
|
||||
StringBuilder sb = stringBuilder(req);
|
||||
//修改多值的属性格式方便转换
|
||||
String bodyparam = sb.toString();
|
||||
bodyparam = BamboocloudUtils.getPlaintext(bodyparam, "123456", "AES");
|
||||
String p = bodyparam;
|
||||
String z = "[\"";
|
||||
String y = "\"]";
|
||||
bodyparam.indexOf(z);
|
||||
bodyparam.indexOf(y);
|
||||
while (bodyparam.contains(z)) {
|
||||
p = bodyparam.substring(bodyparam.indexOf(z), bodyparam.indexOf(y) + 2).replace(z, "\"").replace(y, "\"").replace("\",\"", ",");
|
||||
bodyparam = bodyparam.substring(0, bodyparam.indexOf(z)) + p + bodyparam.substring(bodyparam.indexOf(y) + 2, bodyparam.length());
|
||||
}
|
||||
logger.info("json--param-->" + bodyparam);
|
||||
Map<String, Object> reqmap = (Map<String, Object>) JSON.parse(bodyparam);
|
||||
String username = (String) reqmap.get("bimRemoteUser");
|
||||
String password = (String) reqmap.get("bimRemotePwd");
|
||||
|
||||
if (BamboocloudUtils.checkUsernamePassword(username, password)) {
|
||||
/**
|
||||
* 新增用户
|
||||
*/
|
||||
//获取用户创建所需的参数
|
||||
// User user = createUpdateUser(reqmap);
|
||||
SysUser user = new SysUser();
|
||||
//用户创建
|
||||
userService.insertUser(user);
|
||||
//获取返回给IAM连接器的唯一标识,用于后续该条数据的更新修改删除
|
||||
String uid = user.getUserId() + "";
|
||||
if (uid != null) {
|
||||
schema.put("uid", uid);
|
||||
schema.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
schema.put("resultCode", "0");
|
||||
schema.put("message", "success");
|
||||
} else {
|
||||
schema.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
schema.put("resultCode", "500");
|
||||
schema.put("message", "账号创建失败");
|
||||
}
|
||||
String mapJson = JSON.toJSONString(schema);
|
||||
mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
|
||||
return mapJson;
|
||||
}
|
||||
schema.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
schema.put("resultCode", "500");
|
||||
schema.put("message", "账号创建失败,请检查连接器配置的参数");
|
||||
String mapJson = JSON.toJSONString(schema);
|
||||
//返回加密的json字符串
|
||||
mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
|
||||
return mapJson;
|
||||
}
|
||||
|
||||
|
||||
// @ApiOperation("修改用户")
|
||||
// @ApiImplicitParam(name = "user", value = "修改用户信息", dataType = "User")
|
||||
@PostMapping("/UserUpdateService")
|
||||
@ResponseBody
|
||||
public String userUpdateService(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||||
|
||||
Map<String, Object> schema = new HashMap<String, Object>();
|
||||
|
||||
JSONObject jsonObject = new JSONObject();
|
||||
|
||||
StringBuilder sb = stringBuilder(req);
|
||||
|
||||
String bodyparam = sb.toString();
|
||||
|
||||
bodyparam = BamboocloudUtils.getPlaintext(bodyparam, "123456", "AES");
|
||||
//修改多值的属性格式方便转换
|
||||
String p = bodyparam;
|
||||
String bdp = bodyparam;
|
||||
String z = "[\"";
|
||||
String y = "\"]";
|
||||
bodyparam.indexOf(z);
|
||||
bodyparam.indexOf(y);
|
||||
while (bodyparam.contains(z)) {
|
||||
p = bodyparam.substring(bodyparam.indexOf(z), bodyparam.indexOf(y) + 2).replace(z, "\"").replace(y, "\"").replace("\",\"", ",");
|
||||
bodyparam = bodyparam.substring(0, bodyparam.indexOf(z)) + p + bodyparam.substring(bodyparam.indexOf(y) + 2, bodyparam.length());
|
||||
}
|
||||
logger.info("json--param-->" + bodyparam);
|
||||
Map<String, Object> reqmap = (Map<String, Object>) JSON.parse(bodyparam);
|
||||
String username = (String) reqmap.get("bimRemoteUser");
|
||||
String password = (String) reqmap.get("bimRemotePwd");
|
||||
if (BamboocloudUtils.checkUsernamePassword(username, password)) {
|
||||
SysUser user = new SysUser();
|
||||
//获取用于更新的参数
|
||||
// user = createUpdateUser(reqmap);
|
||||
//获取用于更新的唯一标识
|
||||
user.setUserId(Long.valueOf(String.valueOf(reqmap.get("bimUid"))));
|
||||
//更新用户
|
||||
userService.updateUser(user);
|
||||
schema.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
schema.put("resultCode", "0");
|
||||
schema.put("message", "success");
|
||||
String mapJson = JSON.toJSONString(schema);
|
||||
mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
|
||||
logger.info("response----->" + schema);
|
||||
return mapJson;
|
||||
}
|
||||
schema.put("bimRequestId", reqmap.get("bimRequestId"));
|
||||
schema.put("resultCode", "500");
|
||||
schema.put("message", "账号更新失败,请检查连接器配置的参数");
|
||||
String mapJson = JSON.toJSONString(schema);
|
||||
mapJson = BamboocloudFacade.encrypt(mapJson, "123456", "AES");
|
||||
logger.info("response----->" + schema);
|
||||
return mapJson;
|
||||
}
|
||||
|
||||
|
||||
public StringBuilder stringBuilder(HttpServletRequest req) {
|
||||
BufferedReader br = null;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String str = "";
|
||||
try {
|
||||
br = req.getReader();
|
||||
while ((str = br.readLine()) != null) {
|
||||
sb.append(str);
|
||||
}
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
if (br != null)
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException eo) {
|
||||
eo.printStackTrace();
|
||||
}
|
||||
} finally {
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb;
|
||||
}
|
||||
|
||||
}
|
||||
|
Binary file not shown.
|
@ -0,0 +1,84 @@
|
|||
package com.ruoyi.project.system.utils;
|
||||
|
||||
import com.banboocloud.Codec.BamboocloudFacade;
|
||||
import com.ruoyi.common.utils.reflect.ReflectUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 竹云提供的工具类
|
||||
*/
|
||||
public abstract class BamboocloudUtils {
|
||||
private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
|
||||
public static boolean checkUsernamePassword(String username, String password) {
|
||||
logger.info("username --->" + username + " password --- >" + password + " ----ok");
|
||||
if("bbcadmin".equals(username)&&"P@ssw0rd".equals(password)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getPlaintext(String ciphertext, String key, String type) {
|
||||
return BamboocloudFacade.decrypt(ciphertext, key, type);
|
||||
}
|
||||
|
||||
public static Boolean verify(Map<String, Object> reqmap, String type) {
|
||||
Map<String, Object> verifymap = new TreeMap<String, Object>();
|
||||
StringBuffer sb = new StringBuffer();
|
||||
Iterator<String> it = reqmap.keySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
String key = (String) it.next();
|
||||
verifymap.put(key, reqmap.get(key));
|
||||
}
|
||||
Iterator<String> ittree = verifymap.keySet().iterator();
|
||||
while (ittree.hasNext()) {
|
||||
String key = (String) ittree.next();
|
||||
if (!"signature".equals(key)) {
|
||||
sb.append(key).append("=").append(verifymap.get(key)).append("&");
|
||||
}
|
||||
}
|
||||
sb.deleteCharAt(sb.length() - 1);
|
||||
System.out.println(reqmap.get("signature") + " now " + sb.toString());
|
||||
return BamboocloudFacade.verify(reqmap.get("signature").toString(), sb.toString(), type);
|
||||
}
|
||||
|
||||
public static String getRequestBody(HttpServletRequest request) {
|
||||
BufferedReader br = null;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String str = "";
|
||||
try {
|
||||
br = request.getReader();
|
||||
while ((str = br.readLine()) != null) {
|
||||
sb.append(str);
|
||||
}
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
if (br != null)
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException eo) {
|
||||
eo.printStackTrace();
|
||||
}
|
||||
} finally {
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.business.message.forest;
|
||||
|
||||
import com.dtflys.forest.annotation.Body;
|
||||
import com.dtflys.forest.annotation.Post;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public interface MyClient {
|
||||
|
||||
@Post("http://218.58.79.146:13080/prod-api/outside/sensorData")
|
||||
String receiveSensorData(@Body("data") String data);
|
||||
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.business.message.tio.utils;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author LemonZuo
|
||||
* @create 2020-04-28 22:17
|
||||
*/
|
||||
@Component
|
||||
public class SpringUtil implements ApplicationContextAware {
|
||||
private static ApplicationContext context;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
context = applicationContext;
|
||||
}
|
||||
|
||||
public static void set(ApplicationContext applicationContext) {
|
||||
context = applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过字节码获取
|
||||
* @param beanClass
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> T getBean(Class<T> beanClass) {
|
||||
return context.getBean(beanClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过BeanName获取
|
||||
* @param beanName
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> T getBean(String beanName) {
|
||||
return (T) context.getBean(beanName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过beanName和字节码获取
|
||||
* @param name
|
||||
* @param beanClass
|
||||
* @param <T>
|
||||
* @return
|
||||
*/
|
||||
public static <T> T getBean(String name, Class<T> beanClass) {
|
||||
return context.getBean(name, beanClass);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue