提交 36bb9350 authored 作者: jianglw's avatar jianglw

添加组态echarts 配置功能

上级 6668fc51
......@@ -170,7 +170,12 @@
<artifactId>ruoyi-quartz</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!--mqtt -->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-mqtt</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
......@@ -209,6 +214,7 @@
<module>ruoyi-quartz</module>
<module>ruoyi-generator</module>
<module>ruoyi-common</module>
<module>ruoyi-mqtt</module>
</modules>
<packaging>pom</packaging>
......
......@@ -54,7 +54,11 @@
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>11.2.0.1.0</version>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
......@@ -66,7 +70,10 @@
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-quartz</artifactId>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-mqtt</artifactId>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
......
package com.ruoyi.web.controller.topology;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.topology.TopologyData;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.core.websocket.WebSocketServer;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.topology.service.ITopologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
......@@ -29,12 +26,10 @@ import java.util.List;
@RequestMapping("/topology")
public class IndexController extends BaseController {
@Value(("${ruoyi.profile}"))
private String profile;
@Autowired
private ITopologyService iTopologyService;
@Autowired
private WebSocketServer webSocketServer;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
......@@ -43,12 +38,13 @@ public class IndexController extends BaseController {
* @param topologyData
* @return AjaxResult
*/
@PreAuthorize("@ss.hasAnyPermi('topology:params:set,topology:index:add,topology:index:edit')")
@PostMapping("/save")
public AjaxResult save(@RequestBody TopologyData topologyData) throws IOException {
List<TopologyData> list =null;
TopologyData t=null;
if (topologyData.getId() == null) {
iTopologyService.saveTopologyToId(topologyData ) ;
iTopologyService.saveTopologyToId(topologyData );
stringRedisTemplate.opsForValue().set(Constants.TOPOLOGY_DATA+topologyData.getId(),JSONObject.toJSONString( topologyData.getData()) );
return AjaxResult.success( topologyData );
}else{
......@@ -62,15 +58,23 @@ public class IndexController extends BaseController {
return AjaxResult.error( "保存失败,请检查id是否存在" );
}
@GetMapping("/preview")
public AjaxResult preview() {
@PreAuthorize("@ss.hasPermi('topology:index:showhide')")
@Log(title = "组态显示/隐藏", businessType = BusinessType.OTHER)
@PostMapping("/updateTopology")
public AjaxResult updateTopology(@RequestBody TopologyData topologyData) throws IOException {
iTopologyService.updateTopologyById(topologyData);
return AjaxResult.success();
}
@PreAuthorize( "@ss.hasAnyPermi('topology:index:list')")
@GetMapping("/list")
public TableDataInfo list() {
startPage();
TopologyData topologyData = new TopologyData();
List<TopologyData> list = iTopologyService.getTopology( topologyData );
for(TopologyData t:list){
t.setData( stringRedisTemplate.opsForValue().get( Constants.TOPOLOGY_DATA+t.getId() ) );
}
return AjaxResult.success( list );
return getDataTable(list);
}
@GetMapping("/getTopology/{id}")
......@@ -82,24 +86,34 @@ public class IndexController extends BaseController {
return AjaxResult.success( t );
}
@PreAuthorize("@ss.hasPermi('topology:index:delete')")
@Log(title = "删除组态", businessType = BusinessType.DELETE)
@DeleteMapping("/deleteTopology/{id}")
public AjaxResult deleteTopology(@PathVariable("id") Integer id) {
if(iTopologyService.deleteTopologyById( id )>0){
stringRedisTemplate.delete( Constants.TOPOLOGY_DATA+id );
return AjaxResult.success();
}
return AjaxResult.error( "删除失败" );
}
@PreAuthorize("@ss.hasPermi('topology:index:deleteTopologyHandle')")
@Log(title = "删除组态参数配置", businessType = BusinessType.DELETE)
@DeleteMapping("/deleteTopologyHandle/{id}")
public AjaxResult deleteTopologyHandle(@PathVariable("id") Integer id){
JSONObject jsonObject=JSONObject.parseObject( stringRedisTemplate.opsForValue().get( Constants.TOPOLOGY_DATA+id ) );
jsonObject.remove( "topologyHandle" );
stringRedisTemplate.opsForValue().set( Constants.TOPOLOGY_DATA+id,jsonObject.toJSONString() );
return AjaxResult.success();
}
@GetMapping("/test")
public void test() throws IOException {
JSONObject jsonObject= JSON.parseObject( "{\n" +
" tag: 'numA', //tag节点\n" +
" fontColor: 'red', //数据颜色\n" +
" text: 'test', //文本内容\n" +
" }" );
webSocketServer.sendInfo(jsonObject.toJSONString() ,"1" );
// JSONObject jsonObject= JSON.parseObject( "{\n" +
// " tag: 'numA', //tag节点\n" +
// " fontColor: 'red', //数据颜色\n" +
// " text: 'test', //文本内容\n" +
// " }" );
// webSocketServer.sendInfo(jsonObject.toJSONString() ,"1" );
System.out.println("他请求成功了");
}
}
package com.ruoyi.web.controller.topology;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.utils.sign.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
/**
* 组态公共调用方法
* @author jianglw
* @version 1.0
* @date 2021/4/7 10:34
*/
@RestController
@RequestMapping("/params")
@Slf4j
public class ParamsController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
*
* @param topologyData
* @param id
* @param tag
* @param fun
* @return
*/
@PostMapping("/addChange")
public AjaxResult addChange(@RequestBody String topologyData){
System.out.println(topologyData);
@GetMapping("/show")
public AjaxResult show(@RequestParam(value = "id") String id,
@RequestParam(value = "tag") String tag,
@RequestParam(value = "fun") String fun){
Integer ids;
try {
ids= Integer.parseInt( RsaUtils.encryptByPrivateKey( id ) );
} catch (Exception e) {
log.error(e.getLocalizedMessage());
e.printStackTrace();
return AjaxResult.error("id解析失败");
}
String value=stringRedisTemplate.opsForValue().get( Constants.TOPOLOGY_DATA+ids );
JSONObject jsonObject=JSONObject.parseObject( value );
JSONObject topologyHandle =jsonObject.getJSONObject( "topologyHandle" );
Integer dataAcquisition =topologyHandle.getInteger( "dataAcquisitionMode" );
return AjaxResult.success();
}
......
......@@ -2,20 +2,36 @@
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://localhost:3306/ry-vue?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
url:
username:
password:
driverClassName:
# 从库数据源
mysql:
# 从数据源开关/默认关闭
enabled: true
url: jdbc:mysql://localhost:3306/d5000?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: root
driverClassName: com.mysql.cj.jdbc.Driver
oracle:
# 从数据源开关/默认关闭
enabled: true
url: jdbc:oracle:thin:@221.180.252.34:1521:xe
username: scott
password: scott
driverClassName: oracle.jdbc.driver.OracleDriver
# 初始连接数
initialSize: 5
# 最小连接池数量
......
......@@ -96,8 +96,8 @@ token:
header: Authorization
# 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期(默认30分钟)
expireTime: 30
# 令牌有效期(默认30分钟)30,当前七天
expireTime: 10080
# MyBatis配置
mybatis:
......@@ -131,3 +131,14 @@ xss:
# 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*
# influxdb
influxdb:
enabled: true
url: http://192.168.2.223:8086
token: ruhoz8G-ROLdtjSCb_NYyZ_Oehq55868iMih9iJVL-y71-2Syl08o5d9m2_58-0ywEu77pdOlO62_99dvZf0sw==
bucket: topology
org: sspss
#mqtt
mqtt:
enabled: false
......@@ -105,11 +105,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- mqtt-->
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
......@@ -132,6 +128,30 @@
<artifactId>snakeyaml</artifactId>
<version>1.25</version>
</dependency>
<!-- 共享服务端-->
<dependency>
<groupId>com.hrhx</groupId>
<artifactId>shareserverconconnector</artifactId>
<version>[1.0,)</version>
</dependency>
<!-- influxdb-->
<dependency>
<groupId>com.influxdb</groupId>
<artifactId>influxdb-client-java</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>hrhx-repos</id>
<name>hrhx Repository</name>
<url>http://221.180.252.34:8081/nexus/content/groups/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
\ No newline at end of file
......@@ -10,9 +10,18 @@ public class TopologyData {
private Integer id;
private String name;
private Object data;
private String switchIt;
private String createdTime;
private String alterTime;
public String getSwitchIt() {
return switchIt;
}
public void setSwitchIt(String switchIt) {
this.switchIt = switchIt;
}
public String getCreatedTime() {
return createdTime;
}
......
......@@ -2,6 +2,7 @@ package com.ruoyi.common.core.websocket;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -51,12 +52,11 @@ public class WebSocketServer {
}
log.info("用户连接:"+topologyId+",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("用户:"+topologyId+",网络异常!!!!!!");
}
// try {
// sendMessage( JSONObject.parseObject( AjaxResult.success().toString() ).toJSONString() );
// } catch (IOException e) {
// log.error("用户:"+topologyId+",网络异常!!!!!!");
// }
}
/**
......
......@@ -15,5 +15,13 @@ public enum DataSourceType
/**
* 从库
*/
SLAVE
SLAVE,
/**
* mysql
*/
MYSQL,
/**
* oracle
*/
ORACLE
}
package com.ruoyi.common.enums;
import com.ruoyi.common.topology.handletype.DataParam;
import com.ruoyi.common.topology.handletype.DefaultParam;
import com.ruoyi.common.topology.handletype.DoParam;
import com.ruoyi.common.topology.handletype.NodeLineParamsInt;
/**
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:15
*/
public enum NodeLineParams {
/**
* node/line参数
*/
DO( "do", new DoParam() ),
DATA("data",new DataParam());
public String type;
public NodeLineParamsInt nodeLineParamsInt;
NodeLineParams(String type,NodeLineParamsInt nodeLineParamsInt){
this.type=type;
this.nodeLineParamsInt=nodeLineParamsInt;
}
public static NodeLineParamsInt match(String type){
NodeLineParams[] values = NodeLineParams.values();
for (NodeLineParams value : values) {
if (value.type.equals( type )) {
return value.nodeLineParamsInt;
}
}
return new DefaultParam();
}
}
package com.ruoyi.common.topology.change;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:38
*/
public class AssembleData {
public static Object getData(Handle handle, Map<String,Object> map){
//共享判断与非共享判断
if(map.get( handle.getShareType() ) instanceof Map){
Map<Integer,Object> map1=(Map<Integer,Object>)map.get( handle.getShareType() );
if(!handle.getJudge()) {
return map1.get( Integer.parseInt( handle.getPoint() ) );
}else{
if(handle.getPointValue().contains( "," ) && handle.getChangeValue().contains( "," )){
String[] pointValue= handle.getPointValue().split( "," );
String[] changeValue=handle.getChangeValue().split( "," );
if(pointValue.length==changeValue.length){
for(int i =0;i<pointValue.length;i++){
if(pointValue[i].equals( map1.get( Integer.parseInt(handle.getPoint()) ) )){
return changeValue[i];
}
}
}
}else{
if(handle.getPointValue().equals( map1.get( Integer.parseInt(handle.getPoint()) ) )){
return handle.getChangeValue();
}
}
}
}else{
if(!handle.getJudge()){
return map.get( handle.getPoint() );
}else{
if(handle.getPointValue().contains( "," ) && handle.getChangeValue().contains( "," )){
String[] pointValue= handle.getPointValue().split( "," );
String[] changeValue=handle.getChangeValue().split( "," );
if(pointValue.length==changeValue.length){
for(int i =0;i<pointValue.length;i++){
if(pointValue[i].equals( map.get( handle.getPoint() ) )){
return changeValue[i];
}
}
}
}else{
if(handle.getPointValue().equals( map.get( handle.getPoint() ) )){
return handle.getChangeValue();
}
}
}
}
return "";
}
}
package com.ruoyi.common.topology.change;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/10 11:20
*/
public class ChangePointAndData {
public List<Map<String,Object>> assemble(Map<String,Object> map, JSONObject jsonObject){
Change topologyChange=jsonObject.toJavaObject( Change.class );
return null;
}
}
......@@ -5,13 +5,22 @@ import java.util.List;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/10 11:07
* @date 2021/4/16 10:28
*/
public class Change {
public class ChangeSub {
private String tag;
private Integer type;
private String echarts;
private List<Handle> handle;
public String getEcharts() {
return echarts;
}
public void setEcharts(String echarts) {
this.echarts = echarts;
}
public String getTag() {
return tag;
}
......
package com.ruoyi.common.topology.change;
/**
* Echarts设置
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:04
*/
public class EchartsSet {
private String axis;
private String name;
private String point;
private String seriesType;
public String getAxis() {
return axis;
}
public void setAxis(String axis) {
this.axis = axis;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPoint() {
return point;
}
public void setPoint(String point) {
this.point = point;
}
public String getSeriesType() {
return seriesType;
}
public void setSeriesType(String seriesType) {
this.seriesType = seriesType;
}
}
package com.ruoyi.common.topology.change;
import java.util.List;
/**
* @author jianglw
* @version 1.0
......@@ -8,9 +10,45 @@ package com.ruoyi.common.topology.change;
public class Handle {
private String type;
private String point;
private String shareType;
private Boolean judge;
private String pointValue;
private String changeValue;
private String title;
private Boolean customChart;
private List<EchartsSet> echartsArray;
public Boolean getCustomChart() {
return customChart;
}
public void setCustomChart(Boolean customChart) {
this.customChart = customChart;
}
public List<EchartsSet> getEchartsArray() {
return echartsArray;
}
public void setEchartsArray(List<EchartsSet> echartsArray) {
this.echartsArray = echartsArray;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getShareType() {
return shareType;
}
public void setShareType(String shareType) {
this.shareType = shareType;
}
public String getType() {
return type;
......
package com.ruoyi.common.topology.change;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.enums.NodeLineParams;
import com.ruoyi.common.topology.handletype.NodeLineParamsInt;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 9:41
*/
public class PointAndData {
/**
* 组装数据
* @param map
* @param jsonArray
* @return
*/
public static List<Map<String,Object>> assemble(Map<String,Object> map, JSONArray jsonArray){
List<ChangeSub> list=jsonArray.toJavaList( ChangeSub.class );
List<Map<String,Object>> list1=new LinkedList<>( );
for(ChangeSub changeSub:list){
List<Handle> handleList=changeSub.getHandle();
list1.add( handle( map,handleList,changeSub.getTag(),changeSub.getEcharts() ) );
}
return list1;
}
private static Map<String, Object> handle(Map<String,Object> map, List<Handle> list, String tag,String echarts){
Map<String, Object> map1 =new HashMap<>( );
Map<String, Object> map2=null;
List<Map<String, Object>> list1=null;
for(Handle handle:list){
NodeLineParamsInt nodeLineParamsInt= NodeLineParams.match( handle.getType() );
nodeLineParamsInt.getDataToParams( handle,map,map1,echarts );
// if(handle.getType().equals( "do" )){
// map2=new HashMap<>( );
// list1=new LinkedList<>( );
// map2.put( handle.getType(),AssembleData.getData( handle,map) );
// list1.add( map2 );
// map1.put( "actions", list1);
// }else{
// map1.put( handle.getType(),AssembleData.getData(handle,map) );
// }
}
map1.put( "tag", tag);
return map1;
}
}
package com.ruoyi.common.topology.collect;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:29
*/
public class InfluxdbType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
package com.ruoyi.common.topology.collect;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:34
*/
public class ShareServerType implements CollectTopologyType {
@Override
public Map<String,Object> getData(String param) {
return null;
}
}
package com.ruoyi.common.topology.handletype;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.topology.change.AssembleData;
import com.ruoyi.common.topology.change.EchartsSet;
import com.ruoyi.common.topology.change.Handle;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* 组装echarts数据
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:26
*/
@Slf4j
public class DataParam implements NodeLineParamsInt{
@Override
public void getDataToParams(Handle handle, Map<String, Object> map, Map<String, Object> map1, String echarts) {
//判断是否为自定义图表
if(!handle.getCustomChart()){
map1.put( handle.getType(), AssembleData.getData( handle,map));
}else{
if(StringUtils.isNotBlank( echarts )){
JSONObject jsonObject=JSONObject.parseObject( echarts );
JSONObject jsonObject1=JSONObject.parseObject( echarts ).getJSONObject( "option" );
jsonObject1.getJSONObject( "title" ).put( "text",handle.getTitle() );
List<String> list=new LinkedList<>();
List<String> xList=new LinkedList<>();
List<Map<String,Object>> seriesList=new LinkedList<>();
Map<String,Object> map2=null;
for(EchartsSet echartsSet:handle.getEchartsArray()){
if(echartsSet.getAxis().equals( "yAxis" )){
map2=new HashMap<>();
map2.put( "name",echartsSet.getName() );
map2.put( "type" ,echartsSet.getSeriesType());
map2.put( "data",map.get( echartsSet.getPoint() )+"" );
seriesList.add( map2 );
list.add( echartsSet.getName() );
}
if(echartsSet.getAxis().equals( "xAxis" )){
xList.add( map.get( echartsSet.getPoint() )+"" );
}
}
JSONArray jsonArray=jsonObject1.getJSONArray( "series" );
if(jsonArray.size()==seriesList.size()){
for(int i=0;i<jsonArray.size();i++){
for(Map<String,Object> m:seriesList){
if(jsonArray.getJSONObject( i ).getString( "name" ).equals( m.get( "name" ) )){
JSONObject jsonObject2=jsonArray.getJSONObject( i );
jsonObject2=JSONObject.parseObject( JSON.toJSONString( m ) );
}
}
}
}else{
jsonArray=JSONArray.parseArray( JSON.toJSONString( seriesList ) );
}
jsonObject1.getJSONObject( "xAxis" ).put( "data",xList );
jsonObject1.getJSONObject( "legend" ).put( "data",list );
map1.put( "data", jsonObject.toJSONString());
}else{
log.debug( "未获取到组态中的图表信息");
}
}
//echarts 在canvas上刷新使用
map1.put( "elementRendered", false);
}
}
package com.ruoyi.common.topology.handletype;
import com.ruoyi.common.topology.change.AssembleData;
import com.ruoyi.common.topology.change.Handle;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:28
*/
public class DefaultParam implements NodeLineParamsInt{
@Override
public void getDataToParams(Handle handle, Map<String, Object> map, Map<String, Object> map1, String echarts) {
map1.put( handle.getType(), AssembleData.getData(handle,map) );
}
}
package com.ruoyi.common.topology.handletype;
import com.ruoyi.common.topology.change.AssembleData;
import com.ruoyi.common.topology.change.Handle;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:26
*/
public class DoParam implements NodeLineParamsInt{
@Override
public void getDataToParams(Handle handle, Map<String, Object> map, Map<String, Object> map1, String echarts) {
Map<String,Object> map2=new HashMap<>( );
List<Map<String, Object>> list1=new LinkedList<>( );
map2.put( handle.getType(), AssembleData.getData( handle,map) );
list1.add( map2 );
map1.put( "actions", list1);
}
}
package com.ruoyi.common.topology.handletype;
import com.ruoyi.common.topology.change.Handle;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/6/1 17:17
*/
public interface NodeLineParamsInt {
void getDataToParams(Handle handle, Map<String,Object> map,Map<String,Object> map1,String echarts);
}
......@@ -53,7 +53,7 @@ public class CaptchaConfig
// 边框颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "119,255,0");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
......@@ -71,11 +71,11 @@ public class CaptchaConfig
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 验证码噪点颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
properties.setProperty(KAPTCHA_NOISE_COLOR, "135,206,250");
// 干扰实现类
properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.WaterRipple");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
......
......@@ -48,6 +48,23 @@ public class DruidConfig
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.mysql")
@ConditionalOnProperty(prefix = "spring.datasource.druid.mysql", name = "enabled", havingValue = "true")
public DataSource mysqlDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.oracle")
@ConditionalOnProperty(prefix = "spring.datasource.druid.oracle", name = "enabled", havingValue = "true")
public DataSource oracleDataSource(DruidProperties druidProperties)
{
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
......@@ -56,6 +73,8 @@ public class DruidConfig
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
setDataSource(targetDataSources, DataSourceType.MYSQL.name(), "mysqlDataSource");
setDataSource(targetDataSources, DataSourceType.ORACLE.name(), "oracleDataSource");
return new DynamicDataSource(masterDataSource, targetDataSources);
}
......
package com.ruoyi.framework.config;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.InfluxDBClientOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/27 17:22
*/
@Configuration
public class InfluxDBConfig {
@Value( "${influxdb.url}" )
private String url;
@Value( "${influxdb.token}" )
private String token;
@Value( "${influxdb.bucket}" )
private String bucket;
@Value( "${influxdb.org}" )
private String org;
@Bean(name = "getInfluxDB")
@ConditionalOnProperty(prefix = "influxdb", name = "enabled", havingValue = "true")
public InfluxDBClient getInfluxDB(){
return InfluxDBClientFactory.create(url, token.toCharArray(),org);
}
@Bean(name = "getBucket")
@ConditionalOnProperty(prefix = "influxdb", name = "enabled", havingValue = "true")
public String getBucket(){
return this.bucket;
}
}
......@@ -106,7 +106,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
"/**/*.js"
).permitAll()
.antMatchers("/profile/**").anonymous()
// .antMatchers( "/topology/**" ).anonymous()
.antMatchers( "/topology/test" ).anonymous()
.antMatchers( "/mqttDemo/**" ).anonymous()
.antMatchers( "/imserver/**" ).anonymous()
.antMatchers( "/sendMqttMessage" ).anonymous()
.antMatchers("/common/download**").anonymous()
......
package com.ruoyi.framework.task;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.WriteApi;
import com.influxdb.client.domain.FluxResponse;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.text.DecimalFormat;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* 定时任务调度测试
*
* @author ruoyi
*/
@Component("ryTask")
public class RyTask {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private InfluxDBClient influxDBClient;
@Value( "${influxdb.bucket}" )
private String bucket;
@Value( "${influxdb.org}" )
private String org;
Random random = new Random();
DecimalFormat decimalFormat=new DecimalFormat(".00");
final String str = "total_power,start_power,theory,theory_1,available," +
"a_1,a_2,a_3,a_4,a_5,a_6,a_7,Ua,Ub,Uc,Uab,Ubc,Uca,3U0," +
"p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17," +
"p18,p19,p20,p21,p22,p23,p24,p25,p26,p27,p28,p29,p30,p31,p32," +
"p33,p34,p35,p36,p37,p38,p39,p40,p41,p42";
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
System.out.println( StringUtils.format( "执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i ) );
}
public void ryParams(String params) {
Map<String,Object> map=new LinkedHashMap<>( );
map.put( "tag1",random.nextFloat() );
map.put( "tag2",random.nextFloat() );
Point point = Point
.measurement("mem")
.addFields( map )
.time( Instant.now(), WritePrecision.NS);
try (WriteApi writeApi = influxDBClient.getWriteApi()) {
writeApi.writePoint(bucket, org, point);
}
}
public void ryNoParams() {
// JSONObject jsonObject = new JSONObject();
//
// String[] strArr = str.split( "," );
// for (int i = 0; i < strArr.length; i++) {
// jsonObject.put( strArr[i], decimalFormat.format( random.nextFloat() * 100 ) );
// }
// stringRedisTemplate.opsForValue().set( "gf:data", jsonObject.toJSONString() );
// System.out.println( "执行无参方法" );
JSONObject jsonObject=JSONObject.parseObject( stringRedisTemplate.opsForValue().get( Constants.TOPOLOGY_DATA+"38" ) );
JSONArray jsonArray=jsonObject.getJSONArray( "pens" );
JSONObject jsonObject2=new JSONObject();
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonObject1=jsonArray.getJSONObject( i );
if(jsonObject1.getJSONArray( "tags" ).size()>0 ){
jsonObject2.put( jsonObject1.getJSONArray( "tags" ).getString( 0 ),random.nextBoolean()?"1":"0" );
}
}
System.out.println(jsonObject2.toJSONString());
stringRedisTemplate.opsForValue().set( "fd:data", jsonObject2.toJSONString() );
}
}
package com.ruoyi.quartz.task;
package com.ruoyi.framework.task;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.websocket.WebSocketServer;
import com.ruoyi.common.enums.CollectTopology;
import com.ruoyi.common.topology.collect.CollectTopologyType;
import com.ruoyi.framework.topology.emnus.CollectTopology;
import com.ruoyi.common.topology.change.PointAndData;
import com.ruoyi.framework.topology.collect.CollectTopologyType;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -13,6 +15,7 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
......@@ -25,7 +28,7 @@ public class TopologyTask {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
WebSocketServer webSocketServer;
private WebSocketServer webSocketServer;
private static final Logger log = LoggerFactory.getLogger( TopologyTask.class );
......@@ -46,25 +49,25 @@ public class TopologyTask {
if (StringUtils.isNotEmpty( data ) && stringRedisTemplate.hasKey( Constants.TOPOLOGY_DATA+data )) {
String top = stringRedisTemplate.opsForValue().get( Constants.TOPOLOGY_DATA+data );
JSONObject jsonObject = JSONObject.parseObject( top );
JSONObject topologyHandle =JSONObject.parseObject( jsonObject.get( "topologyHandle" ).toString() );
JSONObject topologyHandle =jsonObject.getJSONObject( "topologyHandle" );
Integer dataAcquisition =topologyHandle.getInteger( "dataAcquisitionMode" );
/**
* 获取数据
*/
CollectTopologyType collectTopologyType=CollectTopology.match( dataAcquisition );
assert collectTopologyType != null;
Map<String,Object> stringObjectMap = collectTopologyType.getData( topologyHandle.getString( "sentence" ) );
Map<String,Object> stringObjectMap = collectTopologyType.getData( topologyHandle.getString( "sentence" ) ,topologyHandle.getJSONArray( "change" ));
/**
* 配置数据
*/
List<Map<String,Object>> list=PointAndData.assemble( stringObjectMap,topologyHandle.getJSONArray( "change" ) );
/**
* mqtt与socket
*/
if (StringUtils.isNotEmpty( jsonObject.getString( "websocket" ) )) {
String webSocket = jsonObject.getString( "websocket" );
try {
webSocketServer.sendInfo( "", webSocket.substring( webSocket.lastIndexOf( "/" ), webSocket.length() ) );
WebSocketServer.sendInfo( JSONArray.toJSONString( list ), webSocket.substring( webSocket.lastIndexOf( "/" )+1, webSocket.length() ) );
} catch (IOException e) {
log.error( "websocket连接失败" );
e.printStackTrace();
......
package com.ruoyi.common.topology.collect;
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import java.util.Map;
......@@ -11,5 +10,5 @@ import java.util.Map;
* @date 2021/4/9 9:55
*/
public interface CollectTopologyType {
public Map<String,Object> getData(String param);
public Map<String,Object> getData(String param,JSONArray jsonArray);
}
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSONArray;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.ruoyi.common.utils.spring.SpringUtils;
import javax.management.Query;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:29
*/
public class InfluxdbType implements CollectTopologyType {
InfluxDBClient influxDBClient= SpringUtils.getBean( "getInfluxDB" );
@Override
public Map<String,Object> getData(String param, JSONArray jsonArray) {
List<FluxTable> list=influxDBClient.getQueryApi().query( param );
Map<String,Object> map1=new LinkedHashMap<>( );
for(FluxTable fluxTable:list){
List<FluxRecord> records = fluxTable.getRecords();
for (FluxRecord fluxRecord : records) {
map1.put( fluxRecord.getField(),fluxRecord.getValue() );
}
}
return map1;
}
}
package com.ruoyi.common.topology.collect;
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.topology.service.impl.MysqlServiceImpl;
import java.util.Map;
......@@ -10,8 +12,9 @@ import java.util.Map;
* @date 2021/4/9 9:57
*/
public class MysqlType implements CollectTopologyType {
MysqlServiceImpl mysqlService= SpringUtils.getBean( MysqlServiceImpl.class );
@Override
public Map<String,Object> getData(String param) {
return null;
public Map<String,Object> getData(String param,JSONArray jsonArray) {
return mysqlService.getMysqlData( param );
}
}
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.topology.service.impl.OracleServiceImpl;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 19:48
*/
public class OracleType implements CollectTopologyType {
OracleServiceImpl oracleService= SpringUtils.getBean( "OracleServiceImpl" );
@Override
public Map<String, Object> getData(String param, JSONArray jsonArray) {
return oracleService.getOracleData( param );
}
}
package com.ruoyi.common.topology.collect;
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.Map;
......@@ -18,7 +16,7 @@ public class RedisType implements CollectTopologyType {
private StringRedisTemplate stringRedisTemplate = SpringUtils.getBean( StringRedisTemplate.class );
@Override
public Map<String,Object> getData(String param) {
public Map<String,Object> getData(String param,JSONArray jsonArray) {
String data =stringRedisTemplate.opsForValue().get( param );
Map<String,Object> map= JSONObject.parseObject( data,Map.class );
return map;
......
package com.ruoyi.framework.topology.collect;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.enums.NodeLineParams;
import com.ruoyi.common.topology.change.EchartsSet;
import com.ruoyi.framework.topology.emnus.ShareDataType;
import com.ruoyi.common.topology.change.ChangeSub;
import com.ruoyi.common.topology.change.Handle;
import shareconnector.netty.ShareServerFactory;
import shareconnector.service.SendAndRequestService;
import java.util.*;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:34
*/
public class ShareServerType implements CollectTopologyType {
ShareServerFactory shareServerFactory=ShareServerFactory.getInstance();
@Override
public Map<String,Object> getData(String param, JSONArray jsonArray) {
String[] params=param.split( ":" );
shareServerFactory.setIp( params[0] ).setPort( Integer.parseInt( params[1] ) );
List<ChangeSub> list=jsonArray.toJavaList( ChangeSub.class );
Map<String, Set<Integer>> map =new LinkedHashMap<>( );
Set<Integer> set=null;
for(ChangeSub changeSub:list) {
List<Handle> handleList = changeSub.getHandle();
for(Handle handle:handleList){
//获取echarts数据
if(handle.getType().equals( NodeLineParams.DATA.type )){
for(EchartsSet echartsSet:handle.getEchartsArray()){
//echarts数据均为Float类型
if(map.containsKey( ShareDataType.FLOAT.name() )){
map.get( handle.getShareType() ).add( Integer.parseInt( echartsSet.getPoint() ) );
}else{
set=new LinkedHashSet<>( );
set.add( Integer.parseInt( echartsSet.getPoint() ) );
map.put( ShareDataType.FLOAT.name(),set );
}
}
//获取除echarts数据
}else{
if(map.containsKey( handle.getShareType() )){
map.get( handle.getShareType() ).add( Integer.parseInt( handle.getPoint() ) );
}else{
set=new LinkedHashSet<>( );
set.add( Integer.parseInt( handle.getPoint() ) );
map.put( handle.getShareType(),set );
}
}
}
}
Map<String,Object> map1=new LinkedHashMap<>( );
for(Map.Entry<String,Set<Integer>> setEntry:map.entrySet()){
Map<Integer,Object> map2=SendAndRequestService.getInstance().getDatas(setEntry.getValue(), ShareDataType.match(setEntry.getKey()) );
map1.put( setEntry.getKey(),map2 );
}
return map1;
}
}
package com.ruoyi.common.enums;
package com.ruoyi.framework.topology.emnus;
import com.ruoyi.common.handlefile.HandleFile;
import com.ruoyi.common.topology.collect.*;
import com.ruoyi.framework.topology.collect.*;
/**
* 获取topology
*
* @author jianglw
* @version 1.0
* @date 2021/4/9 10:31
*/
public enum CollectTopology {
public enum CollectTopology {
/**
* mysql
*/
MYSQL(0,new MysqlType() ),
MYSQL( 0, new MysqlType() ),
ORACLE(1,new OracleType()),
/**
* redis
*/
REDIS(3,new RedisType() ),
REDIS( 3, new RedisType() ),
/**
* influxdb
*/
INFLUXDB(2,new InfluxdbType() ),
INFLUXDB( 2, new InfluxdbType() ),
/**
* shareserver
*/
SHARESERVER(4,new ShareServerType() );
SHARESERVER( 4, new ShareServerType() );
public int i;
public CollectTopologyType collectTopologyType;
CollectTopology(int i, CollectTopologyType collectTopologyType) {
this.i=i;
this.collectTopologyType=collectTopologyType;
this.i = i;
this.collectTopologyType = collectTopologyType;
}
//匹配
public static CollectTopologyType match(int i){
public static CollectTopologyType match(int i) {
CollectTopology[] values = CollectTopology.values();
for (CollectTopology value : values) {
if(value.i==i){
if (value.i == i) {
return value.collectTopologyType;
}
}
......
package com.ruoyi.framework.topology.emnus;
import shareconnector.domain.DataType;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/25 16:19
*/
public enum ShareDataType {
FLOAT("FLOAT", DataType.FLOAT ),
INT("INT", DataType.INTEGER),
BOOLEAN("BOOLEAN", DataType.BOOLEAN),
STRING("STRING", DataType.STRING);
String type;
DataType dataType;
ShareDataType(String type, DataType dataType) {
this.type=type;
this.dataType=dataType;
}
//匹配
public static DataType match(String type) {
ShareDataType[] values = ShareDataType.values();
for (ShareDataType value : values) {
if (value.type .equals( type ) ) {
return value.dataType;
}
}
return null;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.3.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-mqtt</artifactId>
<description>
mqtt
</description>
<dependencies>
<!-- <dependency>-->
<!-- <groupId>io.github.quickmsg</groupId>-->
<!-- <artifactId>smqtt-core</artifactId>-->
<!-- <version>1.0.4</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <artifactId>smqtt-registry-scube</artifactId>-->
<!-- <groupId>io.github.quickmsg</groupId>-->
<!-- <version>1.0.4</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.ruoyi.mqtt.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
/**
* @author jianglw
* @version 1.0
* @date 2021/5/20 9:42
* mqtt配置类 获取mqtt连接
*/
@Slf4j
@Component
public class MqttConfiguration {
@Autowired
private MqttPushClient mqttPushClient;
public static String host="tcp://127.0.0.1:1883";
public static String clientId="mqttjs_cloud";
public static String userName="admin";
public static String password="public";
public static int timeout=1000;
public static int keepAlive=10;
/**
* 连接至mqtt服务器,获取mqtt连接
* @return
*/
@Bean
@Primary
@ConditionalOnProperty(prefix = "mqtt", name = "enabled", havingValue = "true")
public MqttPushClient getMqttPushClient() {
log.info( host,clientId );
//连接至mqtt服务器,获取mqtt连接
mqttPushClient.connect(host, clientId, userName, password, timeout, keepAlive);
//一连接mqtt,就订阅默认需要订阅的主题(如test_queue)
new MqttSubClient(mqttPushClient);
return mqttPushClient;
}
}
package com.ruoyi.mqtt.config;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author jianglw
* @version 1.0
* @date 2021/5/20 9:43
* 消息发送类
*/
@Slf4j
@Component
public class MqttPushClient {
@Autowired
private PushCallback pushCallback;
private static MqttClient client;
public static void setClient(MqttClient client) {
MqttPushClient.client = client;
}
public static MqttClient getClient() {
return client;
}
public void connect(String host, String clientID, String username, String password, int timeout, int keepalive) {
MqttClient client;
try {
client = new MqttClient(host, clientID, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setUserName(username);
options.setPassword(password.toCharArray());
options.setConnectionTimeout(timeout);
options.setKeepAliveInterval(keepalive);
MqttPushClient.setClient(client);
try {
//设置回调类
client.setCallback(pushCallback);
//client.connect(options);
IMqttToken iMqttToken = client.connectWithResult(options);
boolean complete = iMqttToken.isComplete();
log.info("MQTT连接"+(complete?"成功":"失败"));
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发布,默认qos为0,非持久化
*
* @param topic 主题名
* @param pushMessage 消息
*/
public void publish(String topic, String pushMessage) {
publish(0, false, topic, pushMessage);
}
/**
* 发布
*
* @param qos
* @param retained
* @param topic
* @param pushMessage
*/
public void publish(int qos, boolean retained, String topic, String pushMessage) {
MqttMessage message = new MqttMessage();
message.setQos(qos);
message.setRetained(retained);
message.setPayload(pushMessage.getBytes());
MqttTopic mTopic = client.getTopic(topic);
if (null == mTopic) {
log.error("主题不存在:{}",mTopic);
}
try {
mTopic.publish(message);
} catch (Exception e) {
log.error("mqtt发送消息异常:",e);
}
}
}
package com.ruoyi.mqtt.config;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;
/**
* @author jianglw
* @version 1.0
* @date 2021/5/20 9:44
* 消息订阅接收
*/
@Slf4j
@Component
public class MqttSubClient {
public MqttSubClient(MqttPushClient client){
subScribeDataPublishTopic();
}
private void subScribeDataPublishTopic(){
//订阅test_queue主题
subscribe("test_queue");
}
/**
* 订阅某个主题,qos默认为0
*
* @param topic
*/
public void subscribe(String topic) {
subscribe(topic, 0);
}
/**
* 订阅某个主题
*
* @param topic 主题名
* @param qos
*/
public void subscribe(String topic, int qos) {
try {
MqttClient client = MqttPushClient.getClient();
if (client == null) return;
client.subscribe(topic, qos);
log.info("订阅主题:{}",topic);
} catch ( MqttException e) {
e.printStackTrace();
}
}
}
package com.ruoyi.mqtt.config;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author jianglw
* @version 1.0
* @date 2021/5/20 9:44
* 消息回调重连
*/
@Slf4j
@Component
public class PushCallback implements MqttCallback {
@Autowired
private MqttConfiguration mqttConfiguration;
@Override
public void connectionLost(Throwable cause) { // 连接丢失后,一般在这里面进行重连
log.info("连接断开,正在重连");
MqttPushClient mqttPushClient = mqttConfiguration.getMqttPushClient();
if (null != mqttPushClient) {
mqttPushClient.connect(MqttConfiguration.host, MqttConfiguration.clientId, MqttConfiguration.userName,
MqttConfiguration.password, MqttConfiguration.timeout, MqttConfiguration.keepAlive);
log.info("已重连");
}
}
/**
* 发送消息,消息到达后处理方法
* @param token
*/
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
/**
* 订阅主题接收到消息处理方法
* @param topic
* @param message
*/
@Override
public void messageArrived(String topic, MqttMessage message) {
// subscribe后得到的消息会执行到这里面,这里在控制台有输出
log.info("接收消息主题 : " + topic);
log.info("接收消息Qos : " + message.getQos());
log.info("接收消息内容 : " + new String(message.getPayload()));
}
}
package com.ruoyi.mqtt.controller;
import com.ruoyi.mqtt.config.MqttPushClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author jianglw
* @version 1.0
* @date 2021/5/20 10:06
*/
@RestController
@RequestMapping("/mqttDemo")
public class MqttDemoController {
@Autowired
private MqttPushClient mqttPushClient;
/**
* 通过MqttPushClient类publish方法的发送"这是一条测试消息"到名为"test_queue"的主题,如果需要拿到这条消息,
* 需要在MqttSubClient类的subScribeDataPublishTopic方法进行配置和订阅该主题(这个DEMO已经配置好,并在连接mqtt服务器时就已经订阅),
* 配置完成后 PushCallBack类的messageArrived方法会接收到已订阅主题接收到的消息(订阅主题后可以在该方法中处理接收到的消息)
*/
@RequestMapping("/testPublishMessage1")
public void testPublishMessage() {
mqttPushClient.publish("test_queue","这是一条测试消息");
}
@RequestMapping("/testPublishMessage2")
public void testPublishMessage2( @RequestBody String message){
mqttPushClient.publish("test_queue",message);
}
}
/**
* @author jianglw
* @version 1.0
* @date 2021/5/17 17:12
*/
public class Test {
public static void main(String[] args) {
}
}
package com.ruoyi.quartz.task;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
/**
* 定时任务调度测试
*
* @author ruoyi
*/
@Component("ryTask")
public class RyTask
{
public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
{
System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
}
public void ryParams(String params)
{
System.out.println("执行有参方法:" + params);
}
public void ryNoParams()
{
System.out.println("执行无参方法");
}
}
......@@ -61,3 +61,4 @@ public class CronUtils
}
}
}
\ No newline at end of file
package com.ruoyi.topology.mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 10:22
*/
public interface DBMapper {
@Select("${sql}")
Map<String,Object> getDBData(String sql);
}
......@@ -2,8 +2,10 @@ package com.ruoyi.topology.mapper;
import com.ruoyi.common.core.domain.topology.TopologyData;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
......@@ -21,4 +23,7 @@ public interface TopologyMapper {
void updateTopologyById(TopologyData topologyData);
Integer deleteTopologyById(Integer id);
@Select( "${sql}" )
Map<String,Object> getData(String sql);
}
package com.ruoyi.topology.service;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 10:13
*/
public interface IMysqlService {
Map<String,Object> getMysqlData(String sql);
}
package com.ruoyi.topology.service;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 10:19
*/
public interface IOracleService {
Map<String,Object> getOracleData(String sql);
}
......@@ -3,6 +3,7 @@ package com.ruoyi.topology.service;
import com.ruoyi.common.core.domain.topology.TopologyData;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
......@@ -19,4 +20,6 @@ public interface ITopologyService {
void updateTopologyById(TopologyData topologyData);
Integer deleteTopologyById(Integer id);
Map<String,Object> getData(String sql);
}
package com.ruoyi.topology.service.impl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.topology.mapper.DBMapper;
import com.ruoyi.topology.service.IMysqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 10:16
*/
@Service
public class MysqlServiceImpl implements IMysqlService {
@Autowired
private DBMapper dbMapper;
@DataSource(DataSourceType.MYSQL)
@Override
public Map<String, Object> getMysqlData(String sql) {
return dbMapper.getDBData( sql );
}
}
package com.ruoyi.topology.service.impl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.topology.mapper.DBMapper;
import com.ruoyi.topology.service.IOracleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.xml.ws.Action;
import java.util.Map;
/**
* @author jianglw
* @version 1.0
* @date 2021/4/26 10:20
*/
@Service("OracleServiceImpl")
public class OracleServiceImpl implements IOracleService {
@Autowired
private DBMapper dbMapper;
@DataSource(DataSourceType.ORACLE)
@Override
public Map<String, Object> getOracleData(String sql) {
return dbMapper.getDBData( sql );
}
}
package com.ruoyi.topology.service.impl;
import com.ruoyi.common.core.domain.topology.TopologyData;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.topology.mapper.TopologyMapper;
import com.ruoyi.topology.service.ITopologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* @author jianglw
......@@ -24,6 +26,9 @@ public class TopologyService implements ITopologyService {
@Override
public List<TopologyData> getTopology(TopologyData topologyData) {
if(!SecurityUtils.isAdmin( SecurityUtils.getLoginUser().getUser().getUserId() )){
topologyData.setSwitchIt( "1" );
}
return topologyMapper.getTopology(topologyData);
}
......@@ -41,4 +46,9 @@ public class TopologyService implements ITopologyService {
public Integer deleteTopologyById(Integer id) {
return topologyMapper.deleteTopologyById(id);
}
@Override
public Map<String,Object> getData(String sql) {
return topologyMapper.getData(sql);
}
}
......@@ -4,26 +4,28 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.topology.mapper.TopologyMapper">
<insert id="saveTopologyToId" parameterType="com.ruoyi.common.core.domain.topology.TopologyData" useGeneratedKeys="true" keyProperty="id">
insert into topology_user (name,created_time) values (#{name},now())
insert into topology (name,created_time,switch_it) values (#{name},now(),1)
</insert>
<select id="getTopology" parameterType="com.ruoyi.common.core.domain.topology.TopologyData" resultType="com.ruoyi.common.core.domain.topology.TopologyData">
select id,name as name,date_format(created_time,'%Y-%m-%d %H:%i:%s') as createdTime,date_format(alter_time,'%Y-%m-%d %H:%i:%s') as alterTime from topology_user
select id,name as name,date_format(created_time,'%Y-%m-%d %H:%i:%s') as createdTime,date_format(alter_time,'%Y-%m-%d %H:%i:%s') as alterTime,switch_it as switchIt from topology
<where>
<if test="id !=null and id!=''">and id = #{id}</if>
<if test="switchIt !=null and switchIt!=''">and switch_it = #{switchIt}</if>
</where>
</select>
<select id="getTopologyById" resultType="com.ruoyi.common.core.domain.topology.TopologyData">
select id,name as name,date_format(created_time,'%Y-%m-%d %H:%i:%s') as createdTime,date_format(alter_time,'%Y-%m-%d %H:%i:%s') as alterTime from topology_user where id = #{id}
select id,name as name,date_format(created_time,'%Y-%m-%d %H:%i:%s') as createdTime,date_format(alter_time,'%Y-%m-%d %H:%i:%s') as alterTime,switch_it as switchIt from topology where id = #{id}
</select>
<update id="updateTopologyById" parameterType="com.ruoyi.common.core.domain.topology.TopologyData">
update topology_user
update topology
<trim prefix="set" suffixOverrides=",">
<if test="name !=null and name !=''">name = #{name},</if>
<if test="switchIt !=null and switchIt !=''">switch_it = #{switchIt},</if>
alter_time = now()
</trim>
where id =#{id}
</update>
<delete id="deleteTopologyById">
delete from topology_user where id =#{id}
delete from topology where id =#{id}
</delete>
</mapper>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论