118 changed files with 3081 additions and 5090 deletions
@ -1,117 +1,117 @@
|
||||
package com.mh.user.config; |
||||
|
||||
import java.sql.SQLException; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
|
||||
import javax.servlet.Filter; |
||||
import javax.servlet.Servlet; |
||||
import javax.sql.DataSource; |
||||
|
||||
import com.alibaba.druid.wall.WallConfig; |
||||
import com.alibaba.druid.wall.WallFilter; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties; |
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean; |
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean; |
||||
import org.springframework.context.annotation.Bean; |
||||
import org.springframework.context.annotation.Configuration; |
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource; |
||||
import com.alibaba.druid.support.http.StatViewServlet; |
||||
import com.alibaba.druid.support.http.WebStatFilter; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : |
||||
* @updateTime 2020-03-13 |
||||
* @throws : |
||||
*/ |
||||
@Configuration |
||||
@EnableConfigurationProperties({DruidDataSourceProperties.class}) |
||||
public class DruidConfig { |
||||
@Autowired |
||||
private DruidDataSourceProperties properties; |
||||
|
||||
@Bean |
||||
@ConditionalOnMissingBean |
||||
public DataSource druidDataSource() { |
||||
DruidDataSource druidDataSource = new DruidDataSource(); |
||||
druidDataSource.setDriverClassName(properties.getDriverClassName()); |
||||
druidDataSource.setUrl(properties.getUrl()); |
||||
druidDataSource.setUsername(properties.getUsername()); |
||||
druidDataSource.setPassword(properties.getPassword()); |
||||
druidDataSource.setInitialSize(properties.getInitialSize()); |
||||
druidDataSource.setMinIdle(properties.getMinIdle()); |
||||
druidDataSource.setMaxActive(properties.getMaxActive()); |
||||
druidDataSource.setMaxWait(properties.getMaxWait()); |
||||
druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis()); |
||||
druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis()); |
||||
druidDataSource.setValidationQuery(properties.getValidationQuery()); |
||||
druidDataSource.setTestWhileIdle(properties.isTestWhileIdle()); |
||||
druidDataSource.setTestOnBorrow(properties.isTestOnBorrow()); |
||||
druidDataSource.setTestOnReturn(properties.isTestOnReturn()); |
||||
druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements()); |
||||
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize()); |
||||
|
||||
List list=new ArrayList<>(); |
||||
WallFilter wallFilter=new WallFilter(); |
||||
WallConfig config = new WallConfig(); |
||||
//允许一次执行多条语句
|
||||
config.setMultiStatementAllow(true); |
||||
//允许非基本语句的其他语句
|
||||
//config.setNoneBaseStatementAllow(true);
|
||||
wallFilter.setConfig(config); |
||||
list.add(wallFilter); |
||||
druidDataSource.setProxyFilters(list); |
||||
|
||||
try { |
||||
druidDataSource.setFilters(properties.getFilters()); |
||||
druidDataSource.init(); |
||||
} catch (SQLException e) { |
||||
e.printStackTrace(); |
||||
} |
||||
|
||||
return druidDataSource; |
||||
} |
||||
|
||||
/** |
||||
* 注册Servlet信息, 配置监控视图 |
||||
* |
||||
* @return |
||||
*/ |
||||
@Bean |
||||
@ConditionalOnMissingBean |
||||
public ServletRegistrationBean<Servlet> druidServlet() { |
||||
ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*"); |
||||
|
||||
//白名单:
|
||||
// servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
|
||||
//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
|
||||
servletRegistrationBean.addInitParameter("deny","192.168.1.222"); |
||||
//登录查看信息的账号密码, 用于登录Druid监控后台
|
||||
servletRegistrationBean.addInitParameter("loginUsername", "admin"); |
||||
servletRegistrationBean.addInitParameter("loginPassword", "admin"); |
||||
//是否能够重置数据.
|
||||
servletRegistrationBean.addInitParameter("resetEnable", "true"); |
||||
return servletRegistrationBean; |
||||
|
||||
} |
||||
|
||||
/** |
||||
* 注册Filter信息, 监控拦截器 |
||||
* |
||||
* @return |
||||
*/ |
||||
@Bean |
||||
@ConditionalOnMissingBean |
||||
public FilterRegistrationBean<Filter> filterRegistrationBean() { |
||||
FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>(); |
||||
filterRegistrationBean.setFilter(new WebStatFilter()); |
||||
filterRegistrationBean.addUrlPatterns("/*"); |
||||
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); |
||||
return filterRegistrationBean; |
||||
} |
||||
} |
||||
//package com.mh.user.config;
|
||||
//
|
||||
//import java.sql.SQLException;
|
||||
//import java.util.ArrayList;
|
||||
//import java.util.List;
|
||||
//
|
||||
//import javax.servlet.Filter;
|
||||
//import javax.servlet.Servlet;
|
||||
//import javax.sql.DataSource;
|
||||
//
|
||||
//import com.alibaba.druid.wall.WallConfig;
|
||||
//import com.alibaba.druid.wall.WallFilter;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
//import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
//import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import com.alibaba.druid.support.http.StatViewServlet;
|
||||
//import com.alibaba.druid.support.http.WebStatFilter;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title :
|
||||
// * @description :
|
||||
// * @updateTime 2020-03-13
|
||||
// * @throws :
|
||||
// */
|
||||
//@Configuration
|
||||
//@EnableConfigurationProperties({DruidDataSourceProperties.class})
|
||||
//public class DruidConfig {
|
||||
// @Autowired
|
||||
// private DruidDataSourceProperties properties;
|
||||
//
|
||||
// @Bean
|
||||
// @ConditionalOnMissingBean
|
||||
// public DataSource druidDataSource() {
|
||||
// DruidDataSource druidDataSource = new DruidDataSource();
|
||||
// druidDataSource.setDriverClassName(properties.getDriverClassName());
|
||||
// druidDataSource.setUrl(properties.getUrl());
|
||||
// druidDataSource.setUsername(properties.getUsername());
|
||||
// druidDataSource.setPassword(properties.getPassword());
|
||||
// druidDataSource.setInitialSize(properties.getInitialSize());
|
||||
// druidDataSource.setMinIdle(properties.getMinIdle());
|
||||
// druidDataSource.setMaxActive(properties.getMaxActive());
|
||||
// druidDataSource.setMaxWait(properties.getMaxWait());
|
||||
// druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
|
||||
// druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
|
||||
// druidDataSource.setValidationQuery(properties.getValidationQuery());
|
||||
// druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
|
||||
// druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
|
||||
// druidDataSource.setTestOnReturn(properties.isTestOnReturn());
|
||||
// druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
|
||||
// druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
|
||||
//
|
||||
// List list=new ArrayList<>();
|
||||
// WallFilter wallFilter=new WallFilter();
|
||||
// WallConfig config = new WallConfig();
|
||||
// //允许一次执行多条语句
|
||||
// config.setMultiStatementAllow(true);
|
||||
// //允许非基本语句的其他语句
|
||||
// //config.setNoneBaseStatementAllow(true);
|
||||
// wallFilter.setConfig(config);
|
||||
// list.add(wallFilter);
|
||||
// druidDataSource.setProxyFilters(list);
|
||||
//
|
||||
// try {
|
||||
// druidDataSource.setFilters(properties.getFilters());
|
||||
// druidDataSource.init();
|
||||
// } catch (SQLException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
//
|
||||
// return druidDataSource;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 注册Servlet信息, 配置监控视图
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// @Bean
|
||||
// @ConditionalOnMissingBean
|
||||
// public ServletRegistrationBean<Servlet> druidServlet() {
|
||||
// ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*");
|
||||
//
|
||||
// //白名单:
|
||||
//// servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
|
||||
// //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
|
||||
// servletRegistrationBean.addInitParameter("deny","192.168.1.222");
|
||||
// //登录查看信息的账号密码, 用于登录Druid监控后台
|
||||
// servletRegistrationBean.addInitParameter("loginUsername", "admin");
|
||||
// servletRegistrationBean.addInitParameter("loginPassword", "admin");
|
||||
// //是否能够重置数据.
|
||||
// servletRegistrationBean.addInitParameter("resetEnable", "true");
|
||||
// return servletRegistrationBean;
|
||||
//
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 注册Filter信息, 监控拦截器
|
||||
// *
|
||||
// * @return
|
||||
// */
|
||||
// @Bean
|
||||
// @ConditionalOnMissingBean
|
||||
// public FilterRegistrationBean<Filter> filterRegistrationBean() {
|
||||
// FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>();
|
||||
// filterRegistrationBean.setFilter(new WebStatFilter());
|
||||
// filterRegistrationBean.addUrlPatterns("/*");
|
||||
// filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
|
||||
// return filterRegistrationBean;
|
||||
// }
|
||||
//}
|
||||
|
@ -1,172 +1,172 @@
|
||||
package com.mh.user.config; |
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : |
||||
* @updateTime 2020-03-13 |
||||
* @throws : |
||||
*/ |
||||
@ConfigurationProperties(prefix = "spring.datasource.druid") |
||||
public class DruidDataSourceProperties { |
||||
|
||||
// jdbc
|
||||
private String driverClassName; |
||||
private String url; |
||||
private String username; |
||||
private String password; |
||||
// jdbc connection pool
|
||||
private int initialSize; |
||||
private int minIdle; |
||||
private int maxActive = 100; |
||||
private long maxWait; |
||||
private long timeBetweenEvictionRunsMillis; |
||||
private long minEvictableIdleTimeMillis; |
||||
private String validationQuery; |
||||
private boolean testWhileIdle; |
||||
private boolean testOnBorrow; |
||||
private boolean testOnReturn; |
||||
private boolean poolPreparedStatements; |
||||
private int maxPoolPreparedStatementPerConnectionSize; |
||||
// filter
|
||||
private String filters; |
||||
|
||||
public int getInitialSize() { |
||||
return initialSize; |
||||
} |
||||
|
||||
public void setInitialSize(int initialSize) { |
||||
this.initialSize = initialSize; |
||||
} |
||||
|
||||
public int getMinIdle() { |
||||
return minIdle; |
||||
} |
||||
|
||||
public void setMinIdle(int minIdle) { |
||||
this.minIdle = minIdle; |
||||
} |
||||
|
||||
public int getMaxActive() { |
||||
return maxActive; |
||||
} |
||||
|
||||
public void setMaxActive(int maxActive) { |
||||
this.maxActive = maxActive; |
||||
} |
||||
|
||||
public long getMaxWait() { |
||||
return maxWait; |
||||
} |
||||
|
||||
public void setMaxWait(long maxWait) { |
||||
this.maxWait = maxWait; |
||||
} |
||||
|
||||
public long getTimeBetweenEvictionRunsMillis() { |
||||
return timeBetweenEvictionRunsMillis; |
||||
} |
||||
|
||||
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) { |
||||
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; |
||||
} |
||||
|
||||
public long getMinEvictableIdleTimeMillis() { |
||||
return minEvictableIdleTimeMillis; |
||||
} |
||||
|
||||
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { |
||||
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; |
||||
} |
||||
|
||||
public String getValidationQuery() { |
||||
return validationQuery; |
||||
} |
||||
|
||||
public void setValidationQuery(String validationQuery) { |
||||
this.validationQuery = validationQuery; |
||||
} |
||||
|
||||
public boolean isTestWhileIdle() { |
||||
return testWhileIdle; |
||||
} |
||||
|
||||
public void setTestWhileIdle(boolean testWhileIdle) { |
||||
this.testWhileIdle = testWhileIdle; |
||||
} |
||||
|
||||
public boolean isTestOnBorrow() { |
||||
return testOnBorrow; |
||||
} |
||||
|
||||
public void setTestOnBorrow(boolean testOnBorrow) { |
||||
this.testOnBorrow = testOnBorrow; |
||||
} |
||||
|
||||
public boolean isTestOnReturn() { |
||||
return testOnReturn; |
||||
} |
||||
|
||||
public void setTestOnReturn(boolean testOnReturn) { |
||||
this.testOnReturn = testOnReturn; |
||||
} |
||||
|
||||
public boolean isPoolPreparedStatements() { |
||||
return poolPreparedStatements; |
||||
} |
||||
|
||||
public void setPoolPreparedStatements(boolean poolPreparedStatements) { |
||||
this.poolPreparedStatements = poolPreparedStatements; |
||||
} |
||||
|
||||
public int getMaxPoolPreparedStatementPerConnectionSize() { |
||||
return maxPoolPreparedStatementPerConnectionSize; |
||||
} |
||||
|
||||
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { |
||||
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; |
||||
} |
||||
|
||||
public String getFilters() { |
||||
return filters; |
||||
} |
||||
|
||||
public void setFilters(String filters) { |
||||
this.filters = filters; |
||||
} |
||||
|
||||
public String getDriverClassName() { |
||||
return driverClassName; |
||||
} |
||||
|
||||
public void setDriverClassName(String driverClassName) { |
||||
this.driverClassName = driverClassName; |
||||
} |
||||
|
||||
public String getUrl() { |
||||
return url; |
||||
} |
||||
|
||||
public void setUrl(String url) { |
||||
this.url = url; |
||||
} |
||||
|
||||
public String getUsername() { |
||||
return username; |
||||
} |
||||
|
||||
public void setUsername(String username) { |
||||
this.username = username; |
||||
} |
||||
|
||||
public String getPassword() { |
||||
return password; |
||||
} |
||||
|
||||
public void setPassword(String password) { |
||||
this.password = password; |
||||
} |
||||
|
||||
} |
||||
//package com.mh.user.config;
|
||||
//
|
||||
//import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title :
|
||||
// * @description :
|
||||
// * @updateTime 2020-03-13
|
||||
// * @throws :
|
||||
// */
|
||||
//@ConfigurationProperties(prefix = "spring.datasource.druid")
|
||||
//public class DruidDataSourceProperties {
|
||||
//
|
||||
// // jdbc
|
||||
// private String driverClassName;
|
||||
// private String url;
|
||||
// private String username;
|
||||
// private String password;
|
||||
// // jdbc connection pool
|
||||
// private int initialSize;
|
||||
// private int minIdle;
|
||||
// private int maxActive = 100;
|
||||
// private long maxWait;
|
||||
// private long timeBetweenEvictionRunsMillis;
|
||||
// private long minEvictableIdleTimeMillis;
|
||||
// private String validationQuery;
|
||||
// private boolean testWhileIdle;
|
||||
// private boolean testOnBorrow;
|
||||
// private boolean testOnReturn;
|
||||
// private boolean poolPreparedStatements;
|
||||
// private int maxPoolPreparedStatementPerConnectionSize;
|
||||
// // filter
|
||||
// private String filters;
|
||||
//
|
||||
// public int getInitialSize() {
|
||||
// return initialSize;
|
||||
// }
|
||||
//
|
||||
// public void setInitialSize(int initialSize) {
|
||||
// this.initialSize = initialSize;
|
||||
// }
|
||||
//
|
||||
// public int getMinIdle() {
|
||||
// return minIdle;
|
||||
// }
|
||||
//
|
||||
// public void setMinIdle(int minIdle) {
|
||||
// this.minIdle = minIdle;
|
||||
// }
|
||||
//
|
||||
// public int getMaxActive() {
|
||||
// return maxActive;
|
||||
// }
|
||||
//
|
||||
// public void setMaxActive(int maxActive) {
|
||||
// this.maxActive = maxActive;
|
||||
// }
|
||||
//
|
||||
// public long getMaxWait() {
|
||||
// return maxWait;
|
||||
// }
|
||||
//
|
||||
// public void setMaxWait(long maxWait) {
|
||||
// this.maxWait = maxWait;
|
||||
// }
|
||||
//
|
||||
// public long getTimeBetweenEvictionRunsMillis() {
|
||||
// return timeBetweenEvictionRunsMillis;
|
||||
// }
|
||||
//
|
||||
// public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
|
||||
// this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
|
||||
// }
|
||||
//
|
||||
// public long getMinEvictableIdleTimeMillis() {
|
||||
// return minEvictableIdleTimeMillis;
|
||||
// }
|
||||
//
|
||||
// public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
|
||||
// this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
|
||||
// }
|
||||
//
|
||||
// public String getValidationQuery() {
|
||||
// return validationQuery;
|
||||
// }
|
||||
//
|
||||
// public void setValidationQuery(String validationQuery) {
|
||||
// this.validationQuery = validationQuery;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestWhileIdle() {
|
||||
// return testWhileIdle;
|
||||
// }
|
||||
//
|
||||
// public void setTestWhileIdle(boolean testWhileIdle) {
|
||||
// this.testWhileIdle = testWhileIdle;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestOnBorrow() {
|
||||
// return testOnBorrow;
|
||||
// }
|
||||
//
|
||||
// public void setTestOnBorrow(boolean testOnBorrow) {
|
||||
// this.testOnBorrow = testOnBorrow;
|
||||
// }
|
||||
//
|
||||
// public boolean isTestOnReturn() {
|
||||
// return testOnReturn;
|
||||
// }
|
||||
//
|
||||
// public void setTestOnReturn(boolean testOnReturn) {
|
||||
// this.testOnReturn = testOnReturn;
|
||||
// }
|
||||
//
|
||||
// public boolean isPoolPreparedStatements() {
|
||||
// return poolPreparedStatements;
|
||||
// }
|
||||
//
|
||||
// public void setPoolPreparedStatements(boolean poolPreparedStatements) {
|
||||
// this.poolPreparedStatements = poolPreparedStatements;
|
||||
// }
|
||||
//
|
||||
// public int getMaxPoolPreparedStatementPerConnectionSize() {
|
||||
// return maxPoolPreparedStatementPerConnectionSize;
|
||||
// }
|
||||
//
|
||||
// public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
|
||||
// this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
|
||||
// }
|
||||
//
|
||||
// public String getFilters() {
|
||||
// return filters;
|
||||
// }
|
||||
//
|
||||
// public void setFilters(String filters) {
|
||||
// this.filters = filters;
|
||||
// }
|
||||
//
|
||||
// public String getDriverClassName() {
|
||||
// return driverClassName;
|
||||
// }
|
||||
//
|
||||
// public void setDriverClassName(String driverClassName) {
|
||||
// this.driverClassName = driverClassName;
|
||||
// }
|
||||
//
|
||||
// public String getUrl() {
|
||||
// return url;
|
||||
// }
|
||||
//
|
||||
// public void setUrl(String url) {
|
||||
// this.url = url;
|
||||
// }
|
||||
//
|
||||
// public String getUsername() {
|
||||
// return username;
|
||||
// }
|
||||
//
|
||||
// public void setUsername(String username) {
|
||||
// this.username = username;
|
||||
// }
|
||||
//
|
||||
// public String getPassword() {
|
||||
// return password;
|
||||
// }
|
||||
//
|
||||
// public void setPassword(String password) {
|
||||
// this.password = password;
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
@ -1,17 +1,17 @@
|
||||
package com.mh.user.config; |
||||
|
||||
import com.alibaba.druid.support.http.StatViewServlet; |
||||
|
||||
/** |
||||
* druid监控视图配置 |
||||
*/ |
||||
//@WebServlet(urlPatterns = "/druid/*", initParams={
|
||||
// @WebInitParam(name="allow",value="192.168.6.195"), // IP白名单 (没有配置或者为空,则允许所有访问)
|
||||
// @WebInitParam(name="deny",value="192.168.6.73"), // IP黑名单 (存在共同时,deny优先于allow)
|
||||
// @WebInitParam(name="loginUsername",value="admin"), // 用户名
|
||||
// @WebInitParam(name="loginPassword",value="admin"), // 密码
|
||||
// @WebInitParam(name="resetEnable",value="true") // 禁用HTML页面上的“Reset All”功能
|
||||
//})
|
||||
public class DruidStatViewServlet extends StatViewServlet { |
||||
private static final long serialVersionUID = 7359758657306626394L; |
||||
} |
||||
//package com.mh.user.config;
|
||||
//
|
||||
//import com.alibaba.druid.support.http.StatViewServlet;
|
||||
//
|
||||
///**
|
||||
// * druid监控视图配置
|
||||
// */
|
||||
////@WebServlet(urlPatterns = "/druid/*", initParams={
|
||||
//// @WebInitParam(name="allow",value="192.168.6.195"), // IP白名单 (没有配置或者为空,则允许所有访问)
|
||||
//// @WebInitParam(name="deny",value="192.168.6.73"), // IP黑名单 (存在共同时,deny优先于allow)
|
||||
//// @WebInitParam(name="loginUsername",value="admin"), // 用户名
|
||||
//// @WebInitParam(name="loginPassword",value="admin"), // 密码
|
||||
//// @WebInitParam(name="resetEnable",value="true") // 禁用HTML页面上的“Reset All”功能
|
||||
////})
|
||||
//public class DruidStatViewServlet extends StatViewServlet {
|
||||
// private static final long serialVersionUID = 7359758657306626394L;
|
||||
//}
|
@ -1,54 +1,53 @@
|
||||
package com.mh.user.config; |
||||
|
||||
import com.mh.user.job.JobFactory; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.Scheduler; |
||||
import org.springframework.context.annotation.Bean; |
||||
import org.springframework.context.annotation.Configuration; |
||||
import org.springframework.scheduling.quartz.SchedulerFactoryBean; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : Quartz配置 |
||||
* @description : |
||||
* @updateTime 2020-04-03 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
@Configuration |
||||
public class QuartzConfig { |
||||
|
||||
private JobFactory jobFactory; |
||||
|
||||
/** |
||||
* @author jinhaoxun |
||||
* @description 构造器 |
||||
* @param jobFactory |
||||
*/ |
||||
public QuartzConfig(JobFactory jobFactory){ |
||||
this.jobFactory = jobFactory; |
||||
} |
||||
|
||||
/** |
||||
* @author jinhaoxun |
||||
* @description 配置SchedulerFactoryBean,将一个方法产生为Bean并交给Spring容器管理 |
||||
* @return SchedulerFactoryBean |
||||
*/ |
||||
@Bean |
||||
public SchedulerFactoryBean schedulerFactoryBean() { |
||||
// log.info("开始注入定时任务调度器工厂...");
|
||||
System.out.println("开始注入定时任务调度器工厂..."); |
||||
SchedulerFactoryBean factory = new SchedulerFactoryBean();// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
|
||||
factory.setJobFactory(jobFactory);// 设置自定义Job Factory,用于Spring管理Job bean
|
||||
factory.setOverwriteExistingJobs(true);// 覆盖存在的定时任务
|
||||
factory.setStartupDelay(30); //延时30秒启动定时任务,避免系统未完全启动却开始执行定时任务的情况
|
||||
// log.info("注入定时任务调度器工厂成功!");
|
||||
System.out.println("注入定时任务调度器工厂成功!"); |
||||
return factory; |
||||
} |
||||
|
||||
@Bean(name = "scheduler") |
||||
public Scheduler scheduler() { |
||||
return schedulerFactoryBean().getScheduler(); |
||||
} |
||||
} |
||||
//package com.mh.user.config;
|
||||
//
|
||||
//import lombok.extern.slf4j.Slf4j;
|
||||
//import org.quartz.Scheduler;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.scheduling.quartz.SchedulerFactoryBean;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title : Quartz配置
|
||||
// * @description :
|
||||
// * @updateTime 2020-04-03
|
||||
// * @throws :
|
||||
// */
|
||||
//@Slf4j
|
||||
//@Configuration
|
||||
//public class QuartzConfig {
|
||||
//
|
||||
// private JobFactory jobFactory;
|
||||
//
|
||||
// /**
|
||||
// * @author jinhaoxun
|
||||
// * @description 构造器
|
||||
// * @param jobFactory
|
||||
// */
|
||||
// public QuartzConfig(JobFactory jobFactory){
|
||||
// this.jobFactory = jobFactory;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @author jinhaoxun
|
||||
// * @description 配置SchedulerFactoryBean,将一个方法产生为Bean并交给Spring容器管理
|
||||
// * @return SchedulerFactoryBean
|
||||
// */
|
||||
// @Bean
|
||||
// public SchedulerFactoryBean schedulerFactoryBean() {
|
||||
//// log.info("开始注入定时任务调度器工厂...");
|
||||
// System.out.println("开始注入定时任务调度器工厂...");
|
||||
// SchedulerFactoryBean factory = new SchedulerFactoryBean();// Spring提供SchedulerFactoryBean为Scheduler提供配置信息,并被Spring容器管理其生命周期
|
||||
// factory.setJobFactory(jobFactory);// 设置自定义Job Factory,用于Spring管理Job bean
|
||||
// factory.setOverwriteExistingJobs(true);// 覆盖存在的定时任务
|
||||
// factory.setStartupDelay(30); //延时30秒启动定时任务,避免系统未完全启动却开始执行定时任务的情况
|
||||
//// log.info("注入定时任务调度器工厂成功!");
|
||||
// System.out.println("注入定时任务调度器工厂成功!");
|
||||
// return factory;
|
||||
// }
|
||||
//
|
||||
// @Bean(name = "scheduler")
|
||||
// public Scheduler scheduler() {
|
||||
// return schedulerFactoryBean().getScheduler();
|
||||
// }
|
||||
//}
|
||||
|
@ -1,299 +1,296 @@
|
||||
package com.mh.user.controller; |
||||
|
||||
import com.alibaba.fastjson.JSONObject; |
||||
import com.mh.common.http.HttpResult; |
||||
import com.mh.user.annotation.SysLogger; |
||||
import com.mh.user.dto.DeviceMessageDTO; |
||||
import com.mh.user.entity.*; |
||||
import com.mh.user.manage.QuartzManager; |
||||
import com.mh.user.netty.NettyChillerControlClient; |
||||
import com.mh.user.service.chillers.DeviceDisplayService; |
||||
import com.mh.user.constants.Constant; |
||||
import com.mh.user.service.chillers.DeviceManageService; |
||||
import com.mh.user.service.chillers.DeviceParamService; |
||||
import com.mh.user.service.chillers.GatewayManageService; |
||||
import com.mh.user.utils.GetReadOrder485; |
||||
import com.mh.user.utils.QuerySendThread; |
||||
import com.mh.user.constants.SocketMessage; |
||||
import com.mh.user.utils.TimeDifferenceUtil; |
||||
import org.quartz.SchedulerException; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.web.bind.annotation.*; |
||||
|
||||
import javax.annotation.Resource; |
||||
import java.text.ParseException; |
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : 设备管理接口 |
||||
* @updateTime 2020-05-29 |
||||
* @updateTime 2020-07-17 |
||||
* @throws : |
||||
*/ |
||||
@RestController |
||||
public class DeviceManageController { |
||||
|
||||
private final DeviceDisplayService deviceDisplayService; |
||||
private final GatewayManageService gatewayManageService; |
||||
private final DeviceManageService deviceManageService; |
||||
private final DeviceParamService deviceParamService; |
||||
|
||||
public DeviceManageController(DeviceDisplayService deviceDisplayService, GatewayManageService gatewayManageService, DeviceManageService deviceManageService, DeviceParamService deviceParamService) { |
||||
this.deviceDisplayService = deviceDisplayService; |
||||
this.gatewayManageService = gatewayManageService; |
||||
this.deviceManageService = deviceManageService; |
||||
this.deviceParamService = deviceParamService; |
||||
} |
||||
|
||||
@Resource |
||||
QuartzManager quartzManager; |
||||
|
||||
@Autowired |
||||
private SocketMessage socketMessage; |
||||
|
||||
// 查询设备信息状态
|
||||
@GetMapping("/operation/getColdStation") |
||||
public HttpResult getColdStation(@RequestParam(value = "deviceType", required = true) String deviceType) { |
||||
List<DeviceMessageDTO> deviceMessageList = deviceDisplayService.queryDeviceStatus(deviceType); |
||||
Map<String, Object> formValues = new HashMap<>(); |
||||
formValues.put("formValues",deviceMessageList); |
||||
return HttpResult.ok("success", formValues); |
||||
} |
||||
|
||||
// 对设备进行操作处理
|
||||
@PostMapping("/operation/operationDevice") |
||||
public HttpResult operationDevice(@RequestBody List<OrderEntity> changeValues) { |
||||
String result; |
||||
try { |
||||
List<OrderMessageEntity> orderMessageEntityList; |
||||
// type值 0:修改频率, 1:修改开关状态, 2: 关闭冷却泵之前,查询最近关闭的冷却塔时间,3: 群控手自动切换类型,4: 修改温度, 5: 修改压力
|
||||
// // 添加网页发送指令状态 update by ljf on 2020-08-07
|
||||
Constant.CONTROL_WEB_FLAG = true; |
||||
// 暂停采集
|
||||
// quartzManager.pauseJob("DDC","JobDDCGroup");
|
||||
// Thread.sleep(2000);
|
||||
// 修改成不用暂停采集处理
|
||||
GetReadOrder485 getReadOrder485 = new GetReadOrder485(); |
||||
// 判断是否是去关闭冷却泵,如果是,需要检查最近冷却塔有没有关闭并且关闭时间大于8分钟
|
||||
// 判断changeValues大小
|
||||
int size = changeValues.size(); |
||||
int type = changeValues.get(0).getType(); |
||||
if (type == 3 && size == 1) { |
||||
// 生成指令
|
||||
orderMessageEntityList = getReadOrder485.createOrder(changeValues); |
||||
if (orderMessageEntityList.size() != 0) { |
||||
// 开启发送指令
|
||||
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient(); |
||||
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList); |
||||
// 开启线程监测标志
|
||||
QuerySendThread querySendThread = new QuerySendThread(); |
||||
querySendThread.start(); |
||||
if (Constant.SEND_STATUS) { |
||||
result = "success"; |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} else if (type == 2 && size == 1) { |
||||
TimeDifferenceUtil timeDifferenceUtil = new TimeDifferenceUtil(); |
||||
Boolean a = timeDifferenceUtil.timeDifference(socketMessage.getOverTime()); |
||||
if (a) { |
||||
// 生成指令
|
||||
orderMessageEntityList = getReadOrder485.createOrder(changeValues); |
||||
if (orderMessageEntityList.size() != 0) { |
||||
// 开启发送指令
|
||||
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient(); |
||||
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList); |
||||
// 开启线程监测标志
|
||||
QuerySendThread querySendThread = new QuerySendThread(); |
||||
querySendThread.start(); |
||||
if (Constant.SEND_STATUS) { |
||||
result = "success"; |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} else { |
||||
result = "冷却塔关机还没有超过8分钟"; |
||||
} |
||||
} else { |
||||
// 生成指令
|
||||
orderMessageEntityList = getReadOrder485.createOrder(changeValues); |
||||
if (orderMessageEntityList.size() != 0) { |
||||
// 开启发送指令
|
||||
NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient(); |
||||
// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList); |
||||
// 开启线程监测标志
|
||||
QuerySendThread querySendThread = new QuerySendThread(); |
||||
querySendThread.start(); |
||||
if (Constant.SEND_STATUS) { |
||||
result = "success"; |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} else { |
||||
result = "fail"; |
||||
} |
||||
} |
||||
Constant.CONTROL_WEB_FLAG = false; |
||||
// 不需要停止采集
|
||||
// Constant.WEB_FLAG = false;
|
||||
// // 延迟5秒处理,等待线程处理数据
|
||||
Thread.sleep(500); |
||||
// // 重新开启定时采集
|
||||
// quartzManager.resumeAllJob();
|
||||
// quartzManager.resumeJob("DDC","JobDDCGroup");
|
||||
} catch (InterruptedException | ParseException e) { |
||||
e.printStackTrace(); |
||||
result = "fail"; |
||||
} |
||||
// 异常情况处理
|
||||
return HttpResult.ok(result); |
||||
} |
||||
|
||||
/** |
||||
* 查询网关信息 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/gateWay/getGateWayList") |
||||
public HttpResult gateWayList(@RequestBody String requestJson){ |
||||
JSONObject jsonObject =JSONObject.parseObject(requestJson); |
||||
Integer operator = null; |
||||
Integer grade = null; |
||||
if(jsonObject.get("operator") != null){ |
||||
if(jsonObject.get("operator").equals("中国移动")){ |
||||
operator = 0; |
||||
}else if(jsonObject.get("operator").equals("中国联通")){ |
||||
operator = 1; |
||||
}else if(jsonObject.get("operator").equals("中国电信")){ |
||||
operator = 2; |
||||
} |
||||
} |
||||
if(jsonObject.get("grade") != null){ |
||||
if(jsonObject.get("grade").equals("正常")){ |
||||
grade = 0; |
||||
}else if(jsonObject.get("grade").equals("不在线")){ |
||||
grade = 1; |
||||
}else if(jsonObject.get("grade").equals("异常")){ |
||||
grade = 2; |
||||
} |
||||
} |
||||
List<GatewayManageEntity> gateWayList = gatewayManageService.queryByOther(grade,operator); |
||||
JSONObject tableData = new JSONObject(); |
||||
tableData.put("tableData",gateWayList); |
||||
return HttpResult.ok(tableData); |
||||
// System.out.println(requestJson);
|
||||
// return null;
|
||||
} |
||||
|
||||
/** |
||||
* 新增或更新网关信息 |
||||
* @param reqestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/gateWay/addOrUpdateGateWayInfo") |
||||
public HttpResult addOrUpdateGateWayInfo(@RequestBody GatewayManageEntity reqestJson){ |
||||
try { |
||||
System.out.println(reqestJson.toString()); |
||||
gatewayManageService.addOrUpdateGateWayInfo(reqestJson); |
||||
return HttpResult.ok(); |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
return HttpResult.error(e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 删除网关/基表/基表参数信息 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/device/deleteDeviceInfo") |
||||
public HttpResult deleteDeviceInfo(@RequestBody String requestJson){ |
||||
JSONObject jsonObject =JSONObject.parseObject(requestJson); |
||||
System.out.println(jsonObject.get("deviceId")); |
||||
try { |
||||
deviceManageService.deleteDeviceInfo((Integer)jsonObject.get("deviceId"),jsonObject.get("deviceType").toString()); |
||||
return HttpResult.ok(); |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
return HttpResult.error(e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 查询基表管理中的基表数据 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/baseMeter/getBaseMeterList") |
||||
public HttpResult getBaseMeterList(@RequestBody String requestJson){ |
||||
JSONObject jsonObject =JSONObject.parseObject(requestJson); |
||||
List<DeviceManageEntity> list = deviceManageService.getDeviceByOther(jsonObject.get("deviceNum").toString()); |
||||
JSONObject tableData = new JSONObject(); |
||||
tableData.put("tableData",list); |
||||
return HttpResult.ok(tableData); |
||||
} |
||||
|
||||
/** |
||||
* 增加或更新基表信息数据 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/baseMeter/addOrUpdateBaseMeter") |
||||
public HttpResult addOrUpdateBaseMeter(@RequestBody DeviceManageEntity requestJson){ |
||||
try { |
||||
deviceManageService.addOrUpdateBaseMeter(requestJson); |
||||
return HttpResult.ok(); |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
return HttpResult.error("检查输入的设备码是否有误!"); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 查询基表参数管理中的基表参数数据 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/baseMeterParam/getBaseMeterParamList") |
||||
public HttpResult getBaseMeterParamList(@RequestBody String requestJson){ |
||||
JSONObject jsonObject =JSONObject.parseObject(requestJson); |
||||
System.out.println(jsonObject.get("baseMeterType")); |
||||
String baseMeterType = (String) jsonObject.get("baseMeterType"); |
||||
List<DeviceParameterEntity> list = deviceParamService.getBaseMeterParamList(baseMeterType); |
||||
JSONObject tableData = new JSONObject(); |
||||
tableData.put("tableData",list); |
||||
return HttpResult.ok(tableData); |
||||
} |
||||
|
||||
/** |
||||
* 添加或更新基表参数信息 |
||||
* @param requestJson |
||||
* @return |
||||
*/ |
||||
@PostMapping("/baseMeterParam/addOrUpdateBaseMeterParam") |
||||
public HttpResult addOrUpdateBaseMeterParam(@RequestBody DeviceParameterEntity requestJson){ |
||||
try { |
||||
deviceParamService.addOrUpdateBaseMeterParam(requestJson); |
||||
return HttpResult.ok(); |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
return HttpResult.error(e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
|
||||
} |
||||
//package com.mh.user.controller;
|
||||
//
|
||||
//import com.alibaba.fastjson.JSONObject;
|
||||
//import com.mh.common.http.HttpResult;
|
||||
//import com.mh.user.dto.DeviceMessageDTO;
|
||||
//import com.mh.user.entity.*;
|
||||
//import com.mh.user.manage.QuartzManager;
|
||||
//import com.mh.user.service.chillers.DeviceDisplayService;
|
||||
//import com.mh.user.constants.Constant;
|
||||
//import com.mh.user.service.chillers.DeviceManageService;
|
||||
//import com.mh.user.service.chillers.DeviceParamService;
|
||||
//import com.mh.user.service.chillers.GatewayManageService;
|
||||
//import com.mh.user.utils.GetReadOrder485;
|
||||
//import com.mh.user.utils.QuerySendThread;
|
||||
//import com.mh.user.constants.SocketMessage;
|
||||
//import com.mh.user.utils.TimeDifferenceUtil;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.web.bind.annotation.*;
|
||||
//
|
||||
//import javax.annotation.Resource;
|
||||
//import java.text.ParseException;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.List;
|
||||
//import java.util.Map;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title :
|
||||
// * @description : 设备管理接口
|
||||
// * @updateTime 2020-05-29
|
||||
// * @updateTime 2020-07-17
|
||||
// * @throws :
|
||||
// */
|
||||
//@RestController
|
||||
//public class DeviceManageController {
|
||||
//
|
||||
// private final DeviceDisplayService deviceDisplayService;
|
||||
// private final GatewayManageService gatewayManageService;
|
||||
// private final DeviceManageService deviceManageService;
|
||||
// private final DeviceParamService deviceParamService;
|
||||
//
|
||||
// public DeviceManageController(DeviceDisplayService deviceDisplayService, GatewayManageService gatewayManageService, DeviceManageService deviceManageService, DeviceParamService deviceParamService) {
|
||||
// this.deviceDisplayService = deviceDisplayService;
|
||||
// this.gatewayManageService = gatewayManageService;
|
||||
// this.deviceManageService = deviceManageService;
|
||||
// this.deviceParamService = deviceParamService;
|
||||
// }
|
||||
//
|
||||
// @Resource
|
||||
// QuartzManager quartzManager;
|
||||
//
|
||||
// @Autowired
|
||||
// private SocketMessage socketMessage;
|
||||
//
|
||||
// // 查询设备信息状态
|
||||
// @GetMapping("/operation/getColdStation")
|
||||
// public HttpResult getColdStation(@RequestParam(value = "deviceType", required = true) String deviceType) {
|
||||
// List<DeviceMessageDTO> deviceMessageList = deviceDisplayService.queryDeviceStatus(deviceType);
|
||||
// Map<String, Object> formValues = new HashMap<>();
|
||||
// formValues.put("formValues",deviceMessageList);
|
||||
// return HttpResult.ok("success", formValues);
|
||||
// }
|
||||
//
|
||||
// // 对设备进行操作处理
|
||||
// @PostMapping("/operation/operationDevice")
|
||||
// public HttpResult operationDevice(@RequestBody List<OrderEntity> changeValues) {
|
||||
// String result;
|
||||
// try {
|
||||
// List<OrderMessageEntity> orderMessageEntityList;
|
||||
// // type值 0:修改频率, 1:修改开关状态, 2: 关闭冷却泵之前,查询最近关闭的冷却塔时间,3: 群控手自动切换类型,4: 修改温度, 5: 修改压力
|
||||
//// // 添加网页发送指令状态 update by ljf on 2020-08-07
|
||||
// Constant.CONTROL_WEB_FLAG = true;
|
||||
// // 暂停采集
|
||||
//// quartzManager.pauseJob("DDC","JobDDCGroup");
|
||||
//// Thread.sleep(2000);
|
||||
// // 修改成不用暂停采集处理
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// // 判断是否是去关闭冷却泵,如果是,需要检查最近冷却塔有没有关闭并且关闭时间大于8分钟
|
||||
// // 判断changeValues大小
|
||||
// int size = changeValues.size();
|
||||
// int type = changeValues.get(0).getType();
|
||||
// if (type == 3 && size == 1) {
|
||||
// // 生成指令
|
||||
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
|
||||
// if (orderMessageEntityList.size() != 0) {
|
||||
// // 开启发送指令
|
||||
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
|
||||
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
|
||||
// // 开启线程监测标志
|
||||
// QuerySendThread querySendThread = new QuerySendThread();
|
||||
// querySendThread.start();
|
||||
// if (Constant.SEND_STATUS) {
|
||||
// result = "success";
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// } else if (type == 2 && size == 1) {
|
||||
// TimeDifferenceUtil timeDifferenceUtil = new TimeDifferenceUtil();
|
||||
// Boolean a = timeDifferenceUtil.timeDifference(socketMessage.getOverTime());
|
||||
// if (a) {
|
||||
// // 生成指令
|
||||
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
|
||||
// if (orderMessageEntityList.size() != 0) {
|
||||
// // 开启发送指令
|
||||
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
|
||||
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
|
||||
// // 开启线程监测标志
|
||||
// QuerySendThread querySendThread = new QuerySendThread();
|
||||
// querySendThread.start();
|
||||
// if (Constant.SEND_STATUS) {
|
||||
// result = "success";
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// } else {
|
||||
// result = "冷却塔关机还没有超过8分钟";
|
||||
// }
|
||||
// } else {
|
||||
// // 生成指令
|
||||
// orderMessageEntityList = getReadOrder485.createOrder(changeValues);
|
||||
// if (orderMessageEntityList.size() != 0) {
|
||||
// // 开启发送指令
|
||||
// NettyChillerControlClient nettyChillerControlClient = new NettyChillerControlClient();
|
||||
//// nettyChillerControlClient.connect(8081, "192.168.1.131", orderMessageEntityList);
|
||||
// nettyChillerControlClient.connect(socketMessage.getPort(), socketMessage.getIP(), orderMessageEntityList);
|
||||
// // 开启线程监测标志
|
||||
// QuerySendThread querySendThread = new QuerySendThread();
|
||||
// querySendThread.start();
|
||||
// if (Constant.SEND_STATUS) {
|
||||
// result = "success";
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// } else {
|
||||
// result = "fail";
|
||||
// }
|
||||
// }
|
||||
// Constant.CONTROL_WEB_FLAG = false;
|
||||
// // 不需要停止采集
|
||||
//// Constant.WEB_FLAG = false;
|
||||
//// // 延迟5秒处理,等待线程处理数据
|
||||
// Thread.sleep(500);
|
||||
//// // 重新开启定时采集
|
||||
//// quartzManager.resumeAllJob();
|
||||
//// quartzManager.resumeJob("DDC","JobDDCGroup");
|
||||
// } catch (InterruptedException | ParseException e) {
|
||||
// e.printStackTrace();
|
||||
// result = "fail";
|
||||
// }
|
||||
// // 异常情况处理
|
||||
// return HttpResult.ok(result);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 查询网关信息
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/gateWay/getGateWayList")
|
||||
// public HttpResult gateWayList(@RequestBody String requestJson){
|
||||
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
|
||||
// Integer operator = null;
|
||||
// Integer grade = null;
|
||||
// if(jsonObject.get("operator") != null){
|
||||
// if(jsonObject.get("operator").equals("中国移动")){
|
||||
// operator = 0;
|
||||
// }else if(jsonObject.get("operator").equals("中国联通")){
|
||||
// operator = 1;
|
||||
// }else if(jsonObject.get("operator").equals("中国电信")){
|
||||
// operator = 2;
|
||||
// }
|
||||
// }
|
||||
// if(jsonObject.get("grade") != null){
|
||||
// if(jsonObject.get("grade").equals("正常")){
|
||||
// grade = 0;
|
||||
// }else if(jsonObject.get("grade").equals("不在线")){
|
||||
// grade = 1;
|
||||
// }else if(jsonObject.get("grade").equals("异常")){
|
||||
// grade = 2;
|
||||
// }
|
||||
// }
|
||||
// List<GatewayManageEntity> gateWayList = gatewayManageService.queryByOther(grade,operator);
|
||||
// JSONObject tableData = new JSONObject();
|
||||
// tableData.put("tableData",gateWayList);
|
||||
// return HttpResult.ok(tableData);
|
||||
//// System.out.println(requestJson);
|
||||
//// return null;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 新增或更新网关信息
|
||||
// * @param reqestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/gateWay/addOrUpdateGateWayInfo")
|
||||
// public HttpResult addOrUpdateGateWayInfo(@RequestBody GatewayManageEntity reqestJson){
|
||||
// try {
|
||||
// System.out.println(reqestJson.toString());
|
||||
// gatewayManageService.addOrUpdateGateWayInfo(reqestJson);
|
||||
// return HttpResult.ok();
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// return HttpResult.error(e.getMessage());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 删除网关/基表/基表参数信息
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/device/deleteDeviceInfo")
|
||||
// public HttpResult deleteDeviceInfo(@RequestBody String requestJson){
|
||||
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
|
||||
// System.out.println(jsonObject.get("deviceId"));
|
||||
// try {
|
||||
// deviceManageService.deleteDeviceInfo((Integer)jsonObject.get("deviceId"),jsonObject.get("deviceType").toString());
|
||||
// return HttpResult.ok();
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// return HttpResult.error(e.getMessage());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 查询基表管理中的基表数据
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/baseMeter/getBaseMeterList")
|
||||
// public HttpResult getBaseMeterList(@RequestBody String requestJson){
|
||||
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
|
||||
// List<DeviceManageEntity> list = deviceManageService.getDeviceByOther(jsonObject.get("deviceNum").toString());
|
||||
// JSONObject tableData = new JSONObject();
|
||||
// tableData.put("tableData",list);
|
||||
// return HttpResult.ok(tableData);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 增加或更新基表信息数据
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/baseMeter/addOrUpdateBaseMeter")
|
||||
// public HttpResult addOrUpdateBaseMeter(@RequestBody DeviceManageEntity requestJson){
|
||||
// try {
|
||||
// deviceManageService.addOrUpdateBaseMeter(requestJson);
|
||||
// return HttpResult.ok();
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// return HttpResult.error("检查输入的设备码是否有误!");
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 查询基表参数管理中的基表参数数据
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/baseMeterParam/getBaseMeterParamList")
|
||||
// public HttpResult getBaseMeterParamList(@RequestBody String requestJson){
|
||||
// JSONObject jsonObject =JSONObject.parseObject(requestJson);
|
||||
// System.out.println(jsonObject.get("baseMeterType"));
|
||||
// String baseMeterType = (String) jsonObject.get("baseMeterType");
|
||||
// List<DeviceParameterEntity> list = deviceParamService.getBaseMeterParamList(baseMeterType);
|
||||
// JSONObject tableData = new JSONObject();
|
||||
// tableData.put("tableData",list);
|
||||
// return HttpResult.ok(tableData);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 添加或更新基表参数信息
|
||||
// * @param requestJson
|
||||
// * @return
|
||||
// */
|
||||
// @PostMapping("/baseMeterParam/addOrUpdateBaseMeterParam")
|
||||
// public HttpResult addOrUpdateBaseMeterParam(@RequestBody DeviceParameterEntity requestJson){
|
||||
// try {
|
||||
// deviceParamService.addOrUpdateBaseMeterParam(requestJson);
|
||||
// return HttpResult.ok();
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// return HttpResult.error(e.getMessage());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
//}
|
||||
|
@ -1,77 +1,77 @@
|
||||
package com.mh.user.dynamic.config; |
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource; |
||||
import com.mh.user.dynamic.datasource.DynamicDataSource; |
||||
import org.apache.ibatis.session.SqlSessionFactory; |
||||
import org.mybatis.spring.SqlSessionFactoryBean; |
||||
import org.mybatis.spring.SqlSessionTemplate; |
||||
import org.mybatis.spring.annotation.MapperScan; |
||||
import org.springframework.beans.factory.annotation.Qualifier; |
||||
import org.springframework.beans.factory.annotation.Value; |
||||
import org.springframework.context.annotation.Bean; |
||||
import org.springframework.context.annotation.Configuration; |
||||
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; |
||||
|
||||
import javax.sql.DataSource; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @author chison |
||||
* @date 2020-04-02 09:39 |
||||
* @Description |
||||
*/ |
||||
@Configuration |
||||
@MapperScan("com.mh.*.mapper") // 扫描DAO
|
||||
public class DataSourceConfig { |
||||
|
||||
@Value("${spring.datasource.druid.url}") |
||||
private String defaultDBUrl; |
||||
@Value("${spring.datasource.druid.username}") |
||||
private String defaultDBUser; |
||||
@Value("${spring.datasource.druid.password}") |
||||
private String defaultDBPassword; |
||||
@Value("${spring.datasource.druid.driver-class-name}") |
||||
private String defaultDBDreiverName; |
||||
|
||||
|
||||
@Bean |
||||
public DynamicDataSource dynamicDataSource() { |
||||
DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance(); |
||||
|
||||
DruidDataSource defaultDataSource = new DruidDataSource(); |
||||
defaultDataSource.setUrl(defaultDBUrl); |
||||
defaultDataSource.setUsername(defaultDBUser); |
||||
defaultDataSource.setPassword(defaultDBPassword); |
||||
defaultDataSource.setDriverClassName(defaultDBDreiverName); |
||||
|
||||
Map<Object,Object> map = new HashMap<>(); |
||||
map.put("default", defaultDataSource); |
||||
dynamicDataSource.setTargetDataSources(map); |
||||
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource); |
||||
|
||||
return dynamicDataSource; |
||||
} |
||||
|
||||
@Bean |
||||
public SqlSessionFactory sqlSessionFactory( |
||||
@Qualifier("dynamicDataSource") DataSource dynamicDataSource) |
||||
throws Exception { |
||||
SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); |
||||
bean.setDataSource(dynamicDataSource); |
||||
bean.setTypeAliasesPackage("com.mh.*.model"); // 扫描Model
|
||||
|
||||
bean.setMapperLocations(new PathMatchingResourcePatternResolver() |
||||
.getResources("classpath*:**/sqlmapper/*.xml")); |
||||
return bean.getObject(); |
||||
|
||||
} |
||||
|
||||
@Bean(name = "sqlSessionTemplate") |
||||
public SqlSessionTemplate sqlSessionTemplate( |
||||
@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) |
||||
throws Exception { |
||||
return new SqlSessionTemplate(sqlSessionFactory); |
||||
} |
||||
|
||||
} |
||||
//package com.mh.user.dynamic.config;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import com.mh.user.dynamic.datasource.DynamicDataSource;
|
||||
//import org.apache.ibatis.session.SqlSessionFactory;
|
||||
//import org.mybatis.spring.SqlSessionFactoryBean;
|
||||
//import org.mybatis.spring.SqlSessionTemplate;
|
||||
//import org.mybatis.spring.annotation.MapperScan;
|
||||
//import org.springframework.beans.factory.annotation.Qualifier;
|
||||
//import org.springframework.beans.factory.annotation.Value;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
|
||||
//
|
||||
//import javax.sql.DataSource;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
///**
|
||||
// * @author chison
|
||||
// * @date 2020-04-02 09:39
|
||||
// * @Description
|
||||
// */
|
||||
//@Configuration
|
||||
//@MapperScan("com.mh.*.mapper") // 扫描DAO
|
||||
//public class DataSourceConfig {
|
||||
//
|
||||
// @Value("${spring.datasource.druid.url}")
|
||||
// private String defaultDBUrl;
|
||||
// @Value("${spring.datasource.druid.username}")
|
||||
// private String defaultDBUser;
|
||||
// @Value("${spring.datasource.druid.password}")
|
||||
// private String defaultDBPassword;
|
||||
// @Value("${spring.datasource.druid.driver-class-name}")
|
||||
// private String defaultDBDreiverName;
|
||||
//
|
||||
//
|
||||
// @Bean
|
||||
// public DynamicDataSource dynamicDataSource() {
|
||||
// DynamicDataSource dynamicDataSource = DynamicDataSource.getInstance();
|
||||
//
|
||||
// DruidDataSource defaultDataSource = new DruidDataSource();
|
||||
// defaultDataSource.setUrl(defaultDBUrl);
|
||||
// defaultDataSource.setUsername(defaultDBUser);
|
||||
// defaultDataSource.setPassword(defaultDBPassword);
|
||||
// defaultDataSource.setDriverClassName(defaultDBDreiverName);
|
||||
//
|
||||
// Map<Object,Object> map = new HashMap<>();
|
||||
// map.put("default", defaultDataSource);
|
||||
// dynamicDataSource.setTargetDataSources(map);
|
||||
// dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
|
||||
//
|
||||
// return dynamicDataSource;
|
||||
// }
|
||||
//
|
||||
// @Bean
|
||||
// public SqlSessionFactory sqlSessionFactory(
|
||||
// @Qualifier("dynamicDataSource") DataSource dynamicDataSource)
|
||||
// throws Exception {
|
||||
// SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
|
||||
// bean.setDataSource(dynamicDataSource);
|
||||
// bean.setTypeAliasesPackage("com.mh.*.model"); // 扫描Model
|
||||
//
|
||||
// bean.setMapperLocations(new PathMatchingResourcePatternResolver()
|
||||
// .getResources("classpath*:**/sqlmapper/*.xml"));
|
||||
// return bean.getObject();
|
||||
//
|
||||
// }
|
||||
//
|
||||
// @Bean(name = "sqlSessionTemplate")
|
||||
// public SqlSessionTemplate sqlSessionTemplate(
|
||||
// @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory)
|
||||
// throws Exception {
|
||||
// return new SqlSessionTemplate(sqlSessionFactory);
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
@ -1,28 +1,28 @@
|
||||
package com.mh.user.dynamic.config; |
||||
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; |
||||
import org.springframework.context.annotation.Bean; |
||||
import tk.mybatis.spring.mapper.MapperScannerConfigurer; |
||||
|
||||
import java.util.Properties; |
||||
|
||||
/** |
||||
* @author chison |
||||
* @date 2020-04-02 09:40 |
||||
* @Description |
||||
*/ |
||||
@EnableAutoConfiguration |
||||
public class MyBatisMapperScannerConfig { |
||||
@Bean |
||||
public MapperScannerConfigurer mapperScannerConfigurer() { |
||||
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); |
||||
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory"); |
||||
mapperScannerConfigurer.setBasePackage("com.mh.user.mapper"); |
||||
Properties properties = new Properties(); |
||||
properties.setProperty("notEmpty", "false"); |
||||
properties.setProperty("IDENTITY", "MYSQL"); |
||||
mapperScannerConfigurer.setProperties(properties); |
||||
return mapperScannerConfigurer; |
||||
} |
||||
|
||||
} |
||||
//package com.mh.user.dynamic.config;
|
||||
//
|
||||
//import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
//import org.springframework.context.annotation.Bean;
|
||||
//import tk.mybatis.spring.mapper.MapperScannerConfigurer;
|
||||
//
|
||||
//import java.util.Properties;
|
||||
//
|
||||
///**
|
||||
// * @author chison
|
||||
// * @date 2020-04-02 09:40
|
||||
// * @Description
|
||||
// */
|
||||
//@EnableAutoConfiguration
|
||||
//public class MyBatisMapperScannerConfig {
|
||||
// @Bean
|
||||
// public MapperScannerConfigurer mapperScannerConfigurer() {
|
||||
// MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
|
||||
// mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
|
||||
// mapperScannerConfigurer.setBasePackage("com.mh.user.mapper");
|
||||
// Properties properties = new Properties();
|
||||
// properties.setProperty("notEmpty", "false");
|
||||
// properties.setProperty("IDENTITY", "MYSQL");
|
||||
// mapperScannerConfigurer.setProperties(properties);
|
||||
// return mapperScannerConfigurer;
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
@ -1,71 +1,71 @@
|
||||
package com.mh.user.dynamic.datasource; |
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource; |
||||
import com.mh.user.entity.DBEntity; |
||||
|
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
/** |
||||
* @author chison |
||||
* @date 2020-04-02 09:40 |
||||
* @Description |
||||
*/ |
||||
public class DataSourceObject { |
||||
|
||||
private Long MaxWait=6000L; |
||||
private Integer maxActive=10; |
||||
private Long timeBetweenEvictionRunsMillis=6000L; |
||||
|
||||
/** |
||||
* 切换sqlserver数据库,并动态赋值 |
||||
* @param dbInfo |
||||
* @param SourceName |
||||
*/ |
||||
public void SwitchMySQLDataSource(DBEntity dbInfo, String SourceName) { |
||||
System.out.println("mysql进入数据源切换"); |
||||
System.out.println("MaxWait:"+MaxWait); |
||||
DruidDataSource dynamicDataSource = new DruidDataSource(); |
||||
dynamicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); |
||||
dynamicDataSource.setUrl("jdbc:mysql://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+"/"+dbInfo.getDB_Names()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&autoReconnect=true"); |
||||
dynamicDataSource.setUsername(dbInfo.getDB_UserName()); |
||||
dynamicDataSource.setPassword(dbInfo.getDB_Pwd()); |
||||
dynamicDataSource.setMaxWait(MaxWait); |
||||
dynamicDataSource.setMaxActive(maxActive); |
||||
dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); |
||||
|
||||
DynamicDataSource dataSource = DynamicDataSource.getInstance(); |
||||
Map<Object, Object> map=new HashMap<Object, Object>(); |
||||
map.put(SourceName, dynamicDataSource); |
||||
dataSource.setTargetDataSources(map); |
||||
System.out.println(dynamicDataSource.getUrl()); |
||||
System.out.println(SourceName); |
||||
} |
||||
/** |
||||
* 第二个sqlserver数据库 |
||||
* @param dbInfo |
||||
* @param SourceName |
||||
*/ |
||||
public void SwitchSQLServerDataSource(DBEntity dbInfo,String SourceName) { |
||||
System.out.println("进入数据源切换"); |
||||
System.out.println("MaxWait:"+MaxWait); |
||||
DruidDataSource dynamicDataSource = new DruidDataSource(); |
||||
dynamicDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); |
||||
dynamicDataSource.setUrl("jdbc:sqlserver://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+";Databasename="+dbInfo.getDB_Names()); |
||||
dynamicDataSource.setUsername(dbInfo.getDB_UserName()); |
||||
dynamicDataSource.setPassword(dbInfo.getDB_Pwd()); |
||||
System.out.println(dbInfo.getDB_UserName()); |
||||
System.out.println(dbInfo.getDB_Pwd()); |
||||
dynamicDataSource.setMaxWait(MaxWait); |
||||
dynamicDataSource.setMaxActive(maxActive); |
||||
dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); |
||||
|
||||
DynamicDataSource dataSource = DynamicDataSource.getInstance(); |
||||
Map<Object, Object> map=new HashMap<Object, Object>(); |
||||
map.put(SourceName, dynamicDataSource); |
||||
dataSource.setTargetDataSources(map); |
||||
|
||||
System.out.println(dynamicDataSource.getUrl()); |
||||
System.out.println(SourceName); |
||||
} |
||||
} |
||||
//package com.mh.user.dynamic.datasource;
|
||||
//
|
||||
//import com.alibaba.druid.pool.DruidDataSource;
|
||||
//import com.mh.user.entity.DBEntity;
|
||||
//
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Map;
|
||||
//
|
||||
///**
|
||||
// * @author chison
|
||||
// * @date 2020-04-02 09:40
|
||||
// * @Description
|
||||
// */
|
||||
//public class DataSourceObject {
|
||||
//
|
||||
// private Long MaxWait=6000L;
|
||||
// private Integer maxActive=10;
|
||||
// private Long timeBetweenEvictionRunsMillis=6000L;
|
||||
//
|
||||
// /**
|
||||
// * 切换sqlserver数据库,并动态赋值
|
||||
// * @param dbInfo
|
||||
// * @param SourceName
|
||||
// */
|
||||
// public void SwitchMySQLDataSource(DBEntity dbInfo, String SourceName) {
|
||||
// System.out.println("mysql进入数据源切换");
|
||||
// System.out.println("MaxWait:"+MaxWait);
|
||||
// DruidDataSource dynamicDataSource = new DruidDataSource();
|
||||
// dynamicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||
// dynamicDataSource.setUrl("jdbc:mysql://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+"/"+dbInfo.getDB_Names()+"?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&autoReconnect=true");
|
||||
// dynamicDataSource.setUsername(dbInfo.getDB_UserName());
|
||||
// dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
|
||||
// dynamicDataSource.setMaxWait(MaxWait);
|
||||
// dynamicDataSource.setMaxActive(maxActive);
|
||||
// dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
|
||||
//
|
||||
// DynamicDataSource dataSource = DynamicDataSource.getInstance();
|
||||
// Map<Object, Object> map=new HashMap<Object, Object>();
|
||||
// map.put(SourceName, dynamicDataSource);
|
||||
// dataSource.setTargetDataSources(map);
|
||||
// System.out.println(dynamicDataSource.getUrl());
|
||||
// System.out.println(SourceName);
|
||||
// }
|
||||
// /**
|
||||
// * 第二个sqlserver数据库
|
||||
// * @param dbInfo
|
||||
// * @param SourceName
|
||||
// */
|
||||
// public void SwitchSQLServerDataSource(DBEntity dbInfo,String SourceName) {
|
||||
// System.out.println("进入数据源切换");
|
||||
// System.out.println("MaxWait:"+MaxWait);
|
||||
// DruidDataSource dynamicDataSource = new DruidDataSource();
|
||||
// dynamicDataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
|
||||
// dynamicDataSource.setUrl("jdbc:sqlserver://"+dbInfo.getDB_IP()+":"+dbInfo.getDB_Port()+";Databasename="+dbInfo.getDB_Names());
|
||||
// dynamicDataSource.setUsername(dbInfo.getDB_UserName());
|
||||
// dynamicDataSource.setPassword(dbInfo.getDB_Pwd());
|
||||
// System.out.println(dbInfo.getDB_UserName());
|
||||
// System.out.println(dbInfo.getDB_Pwd());
|
||||
// dynamicDataSource.setMaxWait(MaxWait);
|
||||
// dynamicDataSource.setMaxActive(maxActive);
|
||||
// dynamicDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
|
||||
//
|
||||
// DynamicDataSource dataSource = DynamicDataSource.getInstance();
|
||||
// Map<Object, Object> map=new HashMap<Object, Object>();
|
||||
// map.put(SourceName, dynamicDataSource);
|
||||
// dataSource.setTargetDataSources(map);
|
||||
//
|
||||
// System.out.println(dynamicDataSource.getUrl());
|
||||
// System.out.println(SourceName);
|
||||
// }
|
||||
//}
|
||||
|
@ -0,0 +1,34 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.fasterxml.jackson.annotation.JsonFormat; |
||||
import lombok.Data; |
||||
|
||||
import java.util.Date; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 数据结果集基本类 |
||||
* @date 2024-07-10 16:49:24 |
||||
*/ |
||||
@Data |
||||
public class BaseResultEntity { |
||||
|
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
private String deviceAddr; |
||||
private String deviceType; |
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") |
||||
private Date curDate; |
||||
private String curValue; |
||||
private String funCode; |
||||
private String registerAddr; |
||||
private String registerName; |
||||
private int grade; |
||||
private String projectId; |
||||
private String projectName; |
||||
|
||||
} |
@ -1,24 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat; |
||||
import lombok.Data; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
import java.util.Date; |
||||
|
||||
@Data |
||||
public class DataResultChEntity { |
||||
|
||||
private Long id; |
||||
private String deviceAddr; |
||||
private String deviceType; |
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") |
||||
private Date curDate; |
||||
// private String curDate;
|
||||
private String curValue; |
||||
private String funCode; |
||||
private String registerAddr; |
||||
private String registerName; |
||||
private int grade; |
||||
private String projectID; |
||||
private String projectName; |
||||
@TableName("data_result_ch") |
||||
public class DataResultChEntity extends BaseResultEntity { |
||||
} |
||||
|
@ -0,0 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@TableName("data_result_ch") |
||||
public class DataResultChillerEntity extends BaseResultEntity { |
||||
} |
@ -0,0 +1,32 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
import lombok.Data; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.util.Date; |
||||
|
||||
@Data |
||||
@TableName("data_result_cl") |
||||
public class DataResultClBakEntity { |
||||
|
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
private String deviceAddr; |
||||
private String deviceType; |
||||
private Date curDate; |
||||
private BigDecimal curValue; |
||||
private BigDecimal lastValue; |
||||
private Date lastDate; |
||||
private BigDecimal ratio; |
||||
private BigDecimal calcValue; |
||||
private int grade; |
||||
private String havedUpdate; |
||||
private String registerAddr; |
||||
private String registerName; |
||||
private String projectName; |
||||
private String projectId; |
||||
|
||||
} |
@ -1,23 +1,32 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
import lombok.Data; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.util.Date; |
||||
|
||||
@Data |
||||
@TableName("data_result_cl") |
||||
public class DataResultClEntity { |
||||
|
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
private String deviceAddr; |
||||
private String deviceType; |
||||
private double lastValue; |
||||
private Date lastDate; |
||||
private double curValue; |
||||
private Date curDate; |
||||
private double ratio; |
||||
private double calcValue; |
||||
private BigDecimal curValue; |
||||
private BigDecimal lastValue; |
||||
private Date lastDate; |
||||
private BigDecimal ratio; |
||||
private BigDecimal calcValue; |
||||
private int grade; |
||||
private String havedUpdate; |
||||
private String registerAddr; |
||||
private String registerName; |
||||
private String projectName; |
||||
private String projectID; |
||||
private String projectId; |
||||
|
||||
} |
||||
|
@ -1,22 +1,32 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
import lombok.Data; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.util.Date; |
||||
|
||||
@TableName("data_result") |
||||
@Data |
||||
public class DataResultEntity { |
||||
|
||||
/** |
||||
* 主键 |
||||
*/ |
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
private String deviceAddr; |
||||
private String deviceType; |
||||
private double lastValue; |
||||
private BigDecimal lastValue; |
||||
private Date lastDate; |
||||
private double curValue; |
||||
private BigDecimal curValue; |
||||
private Date curDate; |
||||
private double ratio; |
||||
private double calcValue; |
||||
private BigDecimal ratio; |
||||
private BigDecimal calcValue; |
||||
private int grade; |
||||
private String havedUpdate; |
||||
private String projectName; |
||||
private String projectID; |
||||
} |
||||
|
@ -0,0 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@TableName("data_result_fifteen_mi") |
||||
public class DataResultFifteenMiEntity extends BaseResultEntity { |
||||
} |
@ -0,0 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@TableName("data_result_five_mi") |
||||
public class DataResultFiveMiEntity extends BaseResultEntity { |
||||
} |
@ -0,0 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@TableName("data_result_now") |
||||
public class DataResultNowEntity extends BaseResultEntity { |
||||
} |
@ -0,0 +1,7 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@TableName("data_result_one_mi") |
||||
public class DataResultOneMiEntity extends BaseResultEntity { |
||||
} |
@ -0,0 +1,130 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
import lombok.Data; |
||||
|
||||
import java.math.BigDecimal; |
||||
import java.util.Date; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 设备基表安装信息 |
||||
* @date 2024-07-11 13:57:36 |
||||
*/ |
||||
@Data |
||||
@TableName("device_code") |
||||
public class DeviceCodeEntity { |
||||
|
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
|
||||
/** |
||||
* 通讯编号 |
||||
*/ |
||||
private String deviceAddr; |
||||
|
||||
/** |
||||
* 设备类型 |
||||
*/ |
||||
private String deviceType; |
||||
|
||||
/** |
||||
* 串口 |
||||
*/ |
||||
private String dataCom; |
||||
|
||||
/** |
||||
* 端口 |
||||
*/ |
||||
private String dataPort; |
||||
|
||||
/** |
||||
* 设备规格 |
||||
*/ |
||||
private String standard; |
||||
|
||||
/** |
||||
* 安装位置 |
||||
*/ |
||||
private String installPosition; |
||||
|
||||
/** |
||||
* 初始值 |
||||
*/ |
||||
private BigDecimal initValue; |
||||
|
||||
/** |
||||
* 倍率 |
||||
*/ |
||||
private BigDecimal ratio; |
||||
|
||||
/** |
||||
* 是否时总表 |
||||
*/ |
||||
private String isTotal; |
||||
|
||||
/** |
||||
* 是否停用 |
||||
*/ |
||||
private String isForbid; |
||||
|
||||
/** |
||||
* 停用时间 |
||||
*/ |
||||
private Date forbidDate; |
||||
|
||||
/** |
||||
* 上次抄表读数 |
||||
*/ |
||||
private BigDecimal lastValue; |
||||
|
||||
/** |
||||
* 上次抄表时间 |
||||
*/ |
||||
private Date lastDate; |
||||
|
||||
/** |
||||
* 级别 |
||||
*/ |
||||
private int grade; |
||||
|
||||
/** |
||||
* 波特率 |
||||
*/ |
||||
private int baudRate; |
||||
|
||||
/** |
||||
* 项目ID |
||||
*/ |
||||
private String projectId; |
||||
|
||||
/** |
||||
* 设备名称 |
||||
*/ |
||||
private String deviceName; |
||||
|
||||
/** |
||||
* 品牌 |
||||
*/ |
||||
private String brand; |
||||
|
||||
/** |
||||
* 安装时间 |
||||
*/ |
||||
private Date installDate; |
||||
|
||||
/** |
||||
* 奇偶校验 |
||||
*/ |
||||
private String parity; |
||||
|
||||
/** |
||||
* 备注 |
||||
*/ |
||||
private String remarks; |
||||
|
||||
} |
@ -1,14 +1,77 @@
|
||||
package com.mh.user.entity; |
||||
|
||||
import lombok.Data; |
||||
import com.baomidou.mybatisplus.annotation.IdType; |
||||
import com.baomidou.mybatisplus.annotation.TableId; |
||||
import com.baomidou.mybatisplus.annotation.TableName; |
||||
|
||||
@Data |
||||
@TableName("strategy_info") |
||||
public class StrategyInfoEntity { |
||||
|
||||
@TableId(value = "id", type = IdType.AUTO) |
||||
private Long id; |
||||
private String dataAnalysis; |
||||
private String operationOpt; |
||||
private String controlOpt; |
||||
private String projectID; |
||||
private String systemID; |
||||
private String projectId; |
||||
private String systemId; |
||||
|
||||
public Long getId() { |
||||
return id; |
||||
} |
||||
|
||||
public void setId(Long id) { |
||||
this.id = id; |
||||
} |
||||
|
||||
public String getDataAnalysis() { |
||||
return dataAnalysis; |
||||
} |
||||
|
||||
public void setDataAnalysis(String dataAnalysis) { |
||||
this.dataAnalysis = dataAnalysis; |
||||
} |
||||
|
||||
public String getOperationOpt() { |
||||
return operationOpt; |
||||
} |
||||
|
||||
public void setOperationOpt(String operationOpt) { |
||||
this.operationOpt = operationOpt; |
||||
} |
||||
|
||||
public String getControlOpt() { |
||||
return controlOpt; |
||||
} |
||||
|
||||
public void setControlOpt(String controlOpt) { |
||||
this.controlOpt = controlOpt; |
||||
} |
||||
|
||||
public String getProjectId() { |
||||
return projectId; |
||||
} |
||||
|
||||
public void setProjectId(String projectId) { |
||||
this.projectId = projectId; |
||||
} |
||||
|
||||
public String getSystemId() { |
||||
return systemId; |
||||
} |
||||
|
||||
public void setSystemId(String systemId) { |
||||
this.systemId = systemId; |
||||
} |
||||
|
||||
@Override |
||||
public String toString() { |
||||
return "StrategyInfoEntity{" + |
||||
"id=" + id + |
||||
", dataAnalysis='" + dataAnalysis + '\'' + |
||||
", operationOpt='" + operationOpt + '\'' + |
||||
", controlOpt='" + controlOpt + '\'' + |
||||
", projectId='" + projectId + '\'' + |
||||
", systemId='" + systemId + '\'' + |
||||
'}'; |
||||
} |
||||
} |
||||
|
@ -1,39 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import com.mh.user.constants.SocketMessage; |
||||
import lombok.SneakyThrows; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.DisallowConcurrentExecution; |
||||
import org.quartz.Job; |
||||
import org.quartz.JobExecutionContext; |
||||
import org.quartz.JobExecutionException; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :定时采集冷水机组参数 |
||||
* @updateTime 2020-06-24 |
||||
* @throws : |
||||
*/ |
||||
/** |
||||
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行. |
||||
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效 |
||||
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行, |
||||
* 否则会在3秒时再启用新的线程执行 |
||||
*/ |
||||
@DisallowConcurrentExecution |
||||
@Slf4j |
||||
public class JobChillers implements Job { |
||||
|
||||
@Autowired |
||||
private SocketMessage socketMessage; |
||||
|
||||
@SneakyThrows |
||||
@Override |
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { |
||||
log.info("定时采集冷水机组"); |
||||
// NettyChillerClient nettyChillerClient = new NettyChillerClient();
|
||||
|
||||
} |
||||
} |
@ -1,41 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import com.mh.user.netty.NettyClient; |
||||
import com.mh.user.constants.SocketMessage; |
||||
import lombok.SneakyThrows; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.DisallowConcurrentExecution; |
||||
import org.quartz.Job; |
||||
import org.quartz.JobExecutionContext; |
||||
import org.quartz.JobExecutionException; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : 定时采集冷量计任务 |
||||
* @updateTime 2020-05-18 |
||||
* @throws : |
||||
*/ |
||||
/** |
||||
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行. |
||||
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效 |
||||
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行, |
||||
* 否则会在3秒时再启用新的线程执行 |
||||
*/ |
||||
@DisallowConcurrentExecution |
||||
@Slf4j |
||||
public class JobCloud implements Job { |
||||
|
||||
@Autowired |
||||
private SocketMessage socketMessage; |
||||
|
||||
@SneakyThrows |
||||
@Override |
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { |
||||
// 定时采集冷量计
|
||||
log.info("定时采集冷量计"); |
||||
NettyClient nettyClient = new NettyClient(); |
||||
nettyClient.connect(socketMessage.getPort(),socketMessage.getIP()); |
||||
} |
||||
} |
@ -1,39 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import com.mh.user.constants.SocketMessage; |
||||
import com.mh.user.netty.NettyChillerDDCClient; |
||||
import lombok.SneakyThrows; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.DisallowConcurrentExecution; |
||||
import org.quartz.Job; |
||||
import org.quartz.JobExecutionContext; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : 定时采集DDC设备 |
||||
* @description : |
||||
* @updateTime 2020-06-09 |
||||
* @throws : |
||||
*/ |
||||
/** |
||||
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行. |
||||
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效 |
||||
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行, |
||||
* 否则会在3秒时再启用新的线程执行 |
||||
*/ |
||||
@DisallowConcurrentExecution |
||||
@Slf4j |
||||
public class JobDDC implements Job { |
||||
|
||||
@Autowired |
||||
private SocketMessage socketMessage; |
||||
|
||||
@SneakyThrows |
||||
@Override |
||||
public void execute(JobExecutionContext jobExecutionContext) { |
||||
log.info("定时采集DDC设备"); |
||||
// NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient();
|
||||
NettyChillerDDCClient.connect(socketMessage.getPort(), socketMessage.getIP()); |
||||
} |
||||
} |
@ -1,45 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import org.quartz.spi.TriggerFiredBundle; |
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory; |
||||
import org.springframework.scheduling.quartz.AdaptableJobFactory; |
||||
import org.springframework.stereotype.Component; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title :创建JobFactory实例 |
||||
* @description : |
||||
* @updateTime 2020-04-03 |
||||
* @throws : |
||||
*/ |
||||
@Component |
||||
public class JobFactory extends AdaptableJobFactory { |
||||
|
||||
/** |
||||
* AutowireCapableBeanFactory接口是BeanFactory的子类 |
||||
* 可以连接和填充那些生命周期不被Spring管理的已存在的bean实例 |
||||
*/ |
||||
private AutowireCapableBeanFactory factory; |
||||
|
||||
/** |
||||
* @author jinhaoxun |
||||
* @description 构造器 |
||||
* @param factory |
||||
*/ |
||||
public JobFactory(AutowireCapableBeanFactory factory) { |
||||
this.factory = factory; |
||||
} |
||||
|
||||
/** |
||||
* @author jinhaoxun |
||||
* @description 创建Job实例 |
||||
* @param bundle |
||||
* @return Object |
||||
*/ |
||||
@Override |
||||
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { |
||||
Object job = super.createJobInstance(bundle);// 实例化对象
|
||||
factory.autowireBean(job);// 进行注入(Spring管理该Bean)
|
||||
return job;//返回对象
|
||||
} |
||||
} |
@ -1,39 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import com.mh.user.netty.NettyMeterClient; |
||||
import com.mh.user.constants.SocketMessage; |
||||
import lombok.SneakyThrows; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.DisallowConcurrentExecution; |
||||
import org.quartz.Job; |
||||
import org.quartz.JobExecutionContext; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : 定时采集电表数据任务 |
||||
* @updateTime 2020-05-18 |
||||
* @throws : |
||||
*/ |
||||
/** |
||||
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行. |
||||
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效 |
||||
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行, |
||||
* 否则会在3秒时再启用新的线程执行 |
||||
*/ |
||||
@DisallowConcurrentExecution |
||||
@Slf4j |
||||
public class JobMeter implements Job { |
||||
|
||||
@Autowired |
||||
private SocketMessage socketMessage; |
||||
|
||||
@SneakyThrows |
||||
@Override |
||||
public void execute(JobExecutionContext jobExecutionContext) { |
||||
log.info("定时采集电表数据任务开始"); |
||||
NettyMeterClient nettyMeterClient = new NettyMeterClient(); |
||||
nettyMeterClient.connect(socketMessage.getPort(), socketMessage.getIP()); |
||||
} |
||||
} |
@ -1,32 +0,0 @@
|
||||
package com.mh.user.job; |
||||
|
||||
import com.mh.user.constants.Constant; |
||||
import lombok.SneakyThrows; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.quartz.DisallowConcurrentExecution; |
||||
import org.quartz.Job; |
||||
import org.quartz.JobExecutionContext; |
||||
import org.quartz.JobExecutionException; |
||||
|
||||
/** |
||||
* :@DisallowConcurrentExecution : 此标记用在实现Job的类上面,意思是不允许并发执行. |
||||
* :注意org.quartz.threadPool.threadCount线程池中线程的数量至少要多个,否则@DisallowConcurrentExecution不生效 |
||||
* :假如Job的设置时间间隔为3秒,但Job执行时间是5秒,设置@DisallowConcurrentExecution以后程序会等任务执行完毕以后再去执行, |
||||
* 否则会在3秒时再启用新的线程执行 |
||||
*/ |
||||
@DisallowConcurrentExecution |
||||
@Slf4j |
||||
public class JobTest implements Job { |
||||
@SneakyThrows |
||||
@Override |
||||
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { |
||||
for (int i = 0; i < 30; i++) { |
||||
if (Constant.FLAG) { |
||||
break; |
||||
} |
||||
Thread.sleep(1000); |
||||
log.info("第" + i + "个," +jobExecutionContext.getJobDetail()+"---------------------定时任务测试----------------------"); |
||||
} |
||||
|
||||
} |
||||
} |
@ -0,0 +1,73 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultClEntity; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 数据冷量计 |
||||
* @date 2024-07-10 15:20:55 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultChMapper extends BaseMapper<DataResultChEntity> { |
||||
|
||||
//----------------------------------------------------------------------------------------------
|
||||
//保存冷量计数据
|
||||
@Insert("insert into data_result_ch(device_addr,device_type,fun_code,register_addr,register_name,cur_value,cur_date,project_id,grade) values (" + |
||||
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})") |
||||
void saveDataResultCh(DataResultChEntity dataResultChEntity); |
||||
|
||||
@Update("<script>" + |
||||
" update data_result_ch set " + |
||||
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" + |
||||
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" + |
||||
" <if test='funCode!=null'> , fun_code = #{funCode} </if>" + |
||||
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" + |
||||
" <if test='registerName!=null'> , register_name = #{registerName} </if>" + |
||||
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" + |
||||
" <if test='projectID!=null'> , project_id = #{projectID} </if>" + |
||||
" <if test='grade!=null'> , grade = #{grade} </if>" + |
||||
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and device_type=#{deviceType}" + |
||||
"</script>") |
||||
void updateDataResultCh(DataResultChEntity dataResultChEntity); |
||||
|
||||
@Select("select count(*) from data_result_ch " + |
||||
" where cur_date=#{curDate} " + |
||||
" and device_addr=#{deviceAddr} " + |
||||
" and register_addr=#{registerAddr} " + |
||||
" and project_id=#{projectID} " + |
||||
" and grade = #{grade} ") |
||||
int selectDataResultChCount(@Param("curDate") String curDate, |
||||
@Param("deviceAddr") String deviceAddr, |
||||
@Param("registerAddr") String registerAddr, |
||||
@Param("projectID") String projectID, |
||||
@Param("grade") int grade); |
||||
|
||||
@Select("select " + |
||||
" t1.project_id, " + |
||||
" sum(cast (t1.curValue AS decimal(18, 2)))as cur_value, " + |
||||
" t1.cur_date, " + |
||||
" t2.project_name " + |
||||
"from " + |
||||
" data_result_ch t1 " + |
||||
"join project_info t2 on " + |
||||
" t1.project_id = t2.id " + |
||||
"where " + |
||||
" t1.project_id = #{projectID} " + |
||||
" and t1.cur_date >= #{startDate} " + |
||||
" and t1.cur_date <= #{curDate} " + |
||||
"group by " + |
||||
" t1.cur_date, " + |
||||
" t1.project_id, " + |
||||
" t2.project_name " + |
||||
"order by " + |
||||
" t1.cur_date ") |
||||
List<DataResultChEntity> queryDataResultCh(@Param("projectID") String projectID, @Param("startDate") String startDate, @Param("curDate") String curDate); |
||||
|
||||
} |
@ -0,0 +1,105 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultChillerEntity; |
||||
import com.mh.user.mapper.provider.DataResultProvider; |
||||
import com.mh.user.model.ChillerModel; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 主机参数保存 |
||||
* @date 2024-07-10 15:41:15 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultChillerMapper extends BaseMapper<DataResultChillerEntity> { |
||||
|
||||
//保存冷水机数据
|
||||
@Insert("insert into data_result_chiller(device_addr,device_type,fun_code,register_addr,register_name,cur_value,cur_date,project_id,grade) values (" + |
||||
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})") |
||||
void saveDataResultChiller(DataResultChEntity dataResultChEntity); |
||||
|
||||
@Update("<script>" + |
||||
" update data_result_chiller set " + |
||||
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" + |
||||
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" + |
||||
" <if test='funCode!=null'> , fun_code = #{funCode} </if>" + |
||||
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" + |
||||
" <if test='registerName!=null'> , register_name = #{registerName} </if>" + |
||||
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" + |
||||
" <if test='projectID!=null'> , project_id = #{projectID} </if>" + |
||||
" <if test='grade!=null'> , grade = #{grade} </if>" + |
||||
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and register_addr=#{registerAddr} and project_id=#{projectID} " + |
||||
"</script>") |
||||
void updateDataResultChiller(DataResultChEntity dataResultChEntity); |
||||
|
||||
@Select("select count(*) from data_result_chiller where cur_date=#{curDate} " + |
||||
" and device_addr=#{deviceAddr} " + |
||||
" and register_addr=#{registerAddr} " + |
||||
" and project_id=#{projectID} " + |
||||
" and fun_code = #{funCode} ") |
||||
int selectDataResultChillerCount(@Param("curDate") String curDate, |
||||
@Param("deviceAddr") String deviceAddr, |
||||
@Param("registerAddr") String registerAddr, |
||||
@Param("projectID") String projectID, |
||||
@Param("funCode") String funCode); |
||||
|
||||
@Results({ |
||||
@Result(property="deviceAddr",column="deviceAddr"), |
||||
@Result(property="deviceType",column="deviceType"), |
||||
@Result(property="curDate",column="curDate"), |
||||
@Result(property ="curValue",column ="curValue"), |
||||
@Result(property="funCode",column="funCode"), |
||||
@Result(property="registerAddr",column="registerAddr"), |
||||
@Result(property="registerName",column="registerName"), |
||||
@Result(property="grade",column="grade"), |
||||
@Result(property="projectID",column="projectID"), |
||||
@Result(property="projectName",column="project_name") |
||||
}) |
||||
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultChiller") |
||||
List<DataResultChEntity> queryDataResultChiller(@Param("projectID") String projectID, |
||||
@Param("deviceAddr") String deviceAddr, |
||||
@Param("registerName") String registerName, |
||||
@Param("startDate") String startDate, |
||||
@Param("curDate") String curDate, |
||||
@Param("page") int page, |
||||
@Param("limit") int limit); |
||||
|
||||
@SelectProvider(type = DataResultProvider.class,method = "dataResultChillerCount") |
||||
int dataResultChillerCount(@Param("projectID") String projectID, |
||||
@Param("deviceAddr") String deviceAddr, |
||||
@Param("registerName") String registerName, |
||||
@Param("startDate") String startDate, |
||||
@Param("curDate") String curDate); |
||||
|
||||
|
||||
//保存冷水机参数数据
|
||||
@Insert("insert into data_chiller" + |
||||
"(device_addr," + |
||||
"device_name," + |
||||
"run_state," + |
||||
"set_soint," + |
||||
"enter_chw," + |
||||
"leave_chw," + |
||||
"enter_cow," + |
||||
"leave_cow," + |
||||
"power," + |
||||
"rated_power," + |
||||
"chiller_amps," + |
||||
"refrigeration," + |
||||
"rated_ref," + |
||||
"chw_flow," + |
||||
"approach_cow," + |
||||
"approach_chw," + |
||||
"cop," + |
||||
"rated_cop," + |
||||
"copy_date) values (" + |
||||
" #{deviceAddr},#{deviceName},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade})") |
||||
void saveDataChiller(ChillerModel chillerModel); |
||||
|
||||
} |
@ -0,0 +1,35 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultClBakEntity; |
||||
import com.mh.user.entity.DataResultClEntity; |
||||
import org.apache.ibatis.annotations.Insert; |
||||
import org.apache.ibatis.annotations.Mapper; |
||||
import org.apache.ibatis.annotations.Param; |
||||
import org.apache.ibatis.annotations.Select; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 数据冷量计 |
||||
* @date 2024-07-10 15:20:55 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultClBakMapper extends BaseMapper<DataResultClBakEntity> { |
||||
|
||||
@Insert("insert into data_result_cl_bak(device_addr,device_type,project_id,last_value,last_date,cur_value,cur_date,ratio,calc_value,grade,register_addr,register_name) values (" + |
||||
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})") |
||||
void saveDataResultCl_bak(DataResultClEntity dataResultClEntity); |
||||
|
||||
@Select("select count(1) from data_result_cl_bak " + |
||||
" where cur_date = #{curDate} " + |
||||
" and device_addr = #{deviceAddr} " + |
||||
" and registerAddr = #{registerAddr} " + |
||||
" and project_id = #{projectId} ") |
||||
int selectDataResultChBakCount(@Param("curDate") String curDate, |
||||
@Param("deviceAddr") String deviceAddr, |
||||
@Param("registerAddr") String registerAddr, |
||||
@Param("projectId") String projectId); |
||||
|
||||
} |
@ -0,0 +1,42 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultClEntity; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 数据冷量计 |
||||
* @date 2024-07-10 15:20:55 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultClMapper extends BaseMapper<DataResultClEntity> { |
||||
//----------------------------------------------------------------------------------------------
|
||||
//保存冷量计数据
|
||||
@Insert("insert into data_result_cl(device_addr,device_type,project_id,last_value,last_date,cur_value,cur_date,ratio,calc_value,grade,register_addr,register_mame) values (" + |
||||
" #{deviceAddr},#{deviceType},#{projectID},#{lastValue},#{lastDate},#{curValue},#{curDate},#{ratio},#{calcValue},#{grade},#{registerAddr},#{registerName})") |
||||
void saveDataResultCl(DataResultClEntity dataResultClEntity); |
||||
|
||||
@Update("<script>" + |
||||
" update data_result_cl set " + |
||||
" <if test='deviceAddr!=null'> device_addr = #{deviceAddr} </if>" + |
||||
" <if test='deviceType!=null'> , device_type = #{deviceType} </if>" + |
||||
" <if test='projectID!=null'> , project_id = #{projectID} </if>" + |
||||
" <if test='lastValue!=null'> , last_value = #{lastValue} </if>" + |
||||
" <if test='lastDate!=null'> , last_date = #{lastDate} </if>" + |
||||
" <if test='curValue!=null'> , cur_value = #{curValue} </if>" + |
||||
" <if test='ratio!=null'> , ratio = #{ratio} </if>" + |
||||
" <if test='calcValue!=null'> , calc_value = #{calcValue} </if>" + |
||||
" <if test='grade!=null'> , grade = #{grade} </if>" + |
||||
" <if test='registerAddr!=null'> , register_addr = #{registerAddr} </if>" + |
||||
" <if test='registerName!=null'> , register_name = #{registerName} </if>" + |
||||
" where cur_date=#{curDate} and device_addr=#{deviceAddr} and device_type=#{deviceType}" + |
||||
"</script>") |
||||
void updateDataResultCl(DataResultClEntity dataResultClEntity); |
||||
|
||||
} |
@ -0,0 +1,36 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultFifteenMiEntity; |
||||
import com.mh.user.entity.DataResultFiveMiEntity; |
||||
import com.mh.user.mapper.provider.DataResultProvider; |
||||
import org.apache.ibatis.annotations.Mapper; |
||||
import org.apache.ibatis.annotations.Param; |
||||
import org.apache.ibatis.annotations.ResultMap; |
||||
import org.apache.ibatis.annotations.SelectProvider; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 每分钟保存数据 |
||||
* @date 2024-07-10 17:34:30 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultFifteenMiMapper extends BaseMapper<DataResultFifteenMiEntity> { |
||||
|
||||
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFifteenMi") |
||||
List<DataResultChEntity> queryDataResultFifteenMi(@Param("projectID") String projectID, |
||||
@Param("startDate") String startDate, |
||||
@Param("curDate") String curDate, |
||||
@Param("page") int page, |
||||
@Param("limit") int limit); |
||||
|
||||
//@Select("select count(*) from data_result_fifteen_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
|
||||
@SelectProvider(type = DataResultProvider.class,method = "dataResultFifteenMiCount") |
||||
int dataResultFifteenMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate); |
||||
|
||||
} |
@ -0,0 +1,33 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultFiveMiEntity; |
||||
import com.mh.user.entity.DataResultOneMiEntity; |
||||
import com.mh.user.mapper.provider.DataResultProvider; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 每分钟保存数据 |
||||
* @date 2024-07-10 17:34:30 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultFiveMiMapper extends BaseMapper<DataResultFiveMiEntity> { |
||||
|
||||
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultFiveMi") |
||||
List<DataResultChEntity> queryDataResultFiveMi(@Param("projectID") String projectID, |
||||
@Param("startDate") String startDate, |
||||
@Param("curDate") String curDate, |
||||
@Param("page") int page, |
||||
@Param("limit") int limit); |
||||
|
||||
|
||||
// @Select("select count(*) from data_result_five_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
|
||||
@SelectProvider(type = DataResultProvider.class,method = "dataResultFiveMiCount") |
||||
int dataResultFiveMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate); |
||||
} |
@ -0,0 +1,36 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultNowEntity; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 当前记录 |
||||
* @date 2024-07-11 13:41:04 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultNowMapper extends BaseMapper<DataResultNowEntity> { |
||||
|
||||
@Insert("insert into data_result_now(deviceAddr,deviceType,funCode,registerAddr,registerName,curValue,curDate,projectID,grade) values (" + |
||||
" #{deviceAddr},#{deviceType},#{funCode},#{registerAddr},#{registerName},#{curValue},#{curDate},#{projectID},#{grade})") |
||||
void saveDataResultNow(DataResultChEntity dataResultChEntity); |
||||
|
||||
@Delete("delete from data_result_now where deviceAddr=#{deviceAddr} and deviceType = #{deviceType} and registerAddr=#{registerAddr} and projectID=#{projectID}") |
||||
void deleteDataResultNow(@Param("deviceAddr") String deviceAddr, |
||||
@Param("deviceType") String deviceType, |
||||
@Param("registerAddr") String registerAddr, |
||||
@Param("projectID") String projectID); |
||||
|
||||
//实时参数读取
|
||||
@Select("select * from data_result_now where deviceAddr=#{deviceAddr} and deviceType=#{deviceType} and projectID=#{projectID} ") |
||||
List<DataResultChEntity> selectDataResultNow(@Param("deviceAddr") String deviceAddr, |
||||
@Param("deviceType") String deviceType, |
||||
@Param("projectID") String projectID); |
||||
|
||||
} |
@ -0,0 +1,46 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DataResultChEntity; |
||||
import com.mh.user.entity.DataResultOneMiEntity; |
||||
import com.mh.user.mapper.provider.DataResultProvider; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 每分钟保存数据 |
||||
* @date 2024-07-10 17:34:30 |
||||
*/ |
||||
@Mapper |
||||
public interface DataResultOneMiMapper extends BaseMapper<DataResultOneMiEntity> { |
||||
|
||||
//----------------------------------------------------------------------------------------------------
|
||||
@Results(id="rsc", value = { |
||||
@Result(property="deviceAddr",column="deviceAddr"), |
||||
@Result(property="deviceType",column="deviceType"), |
||||
@Result(property="curDate",column="curDate"), |
||||
@Result(property ="curValue",column ="curValue"), |
||||
@Result(property="funCode",column="funCode"), |
||||
@Result(property="registerAddr",column="registerAddr"), |
||||
@Result(property="registerName",column="registerName"), |
||||
@Result(property="grade",column="grade"), |
||||
@Result(property="projectID",column="projectID"), |
||||
@Result(property="projectName",column="project_name") |
||||
}) |
||||
@SelectProvider(type = DataResultProvider.class,method = "queryDataResultOneMi") |
||||
List<DataResultChEntity> queryDataResultOneMi(@Param("projectID") String projectID, |
||||
@Param("startDate") String startDate, |
||||
@Param("curDate") String curDate, |
||||
@Param("page") int page, |
||||
@Param("limit") int limit); |
||||
|
||||
//查询记录数
|
||||
// @Select("select count(*) from data_result_one_mi where projectID=#{projectID} and curDate>=#{startDate} and curDate<=#{curDate} ")
|
||||
@SelectProvider(type = DataResultProvider.class,method = "dataResultOneMiCount") |
||||
int dataResultOneMiCount(@Param("projectID") String projectID,@Param("startDate") String startDate,@Param("curDate") String curDate); |
||||
|
||||
} |
@ -0,0 +1,55 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.DeviceCodeEntity; |
||||
import com.mh.user.model.ChillerModel; |
||||
import com.mh.user.model.DeviceModel; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author LJF |
||||
* @version 1.0 |
||||
* @project mh_esi |
||||
* @description 设备参数mapper |
||||
* @date 2024-07-11 15:37:48 |
||||
*/ |
||||
@Mapper |
||||
public interface DeviceCodeMapper extends BaseMapper<DeviceCodeEntity> { |
||||
|
||||
//查询冷水机设备列表
|
||||
@Results({ |
||||
@Result(column = "device_addr",property = "deviceAddr" ), |
||||
@Result(column = "device_name", property = "deviceName") |
||||
}) |
||||
@Select("select * from device_code where project_id=#{projectID} and device_type='冷水机'") |
||||
List<DeviceModel> selectDevices(@Param("projectID") String projectID); |
||||
|
||||
|
||||
//查询多个冷水机相关信息
|
||||
@Results({ |
||||
@Result(column = "device_addr",property = "deviceAddr" ), |
||||
@Result(column = "device_name", property = "deviceName"), |
||||
@Result(column = "runState", property = "runState"), |
||||
@Result(column = "setPoint", property = "setPoint"), |
||||
@Result(column = "enterChw", property = "enterChw"), |
||||
@Result(column = "leaveChw", property = "leaveChw"), |
||||
@Result(column = "enterCow", property = "enterCow"), |
||||
@Result(column = "leaveCow", property = "leaveCow"), |
||||
@Result(column = "power", property = "power"), |
||||
@Result(column = "ratedPower", property = "ratedPower"), |
||||
@Result(column = "chillerAmps", property = "chillerAmps"), |
||||
@Result(column = "refrigeration", property = "refrigeration"), |
||||
@Result(column = "ratedRef", property = "ratedRef"), |
||||
@Result(column = "chwFlow", property = "chwFlow"), |
||||
@Result(column = "ApproachCow", property = "ApproachCow"), |
||||
@Result(column = "ApproachChw", property = "ApproachChw"), |
||||
@Result(column = "cop", property = "cop"), |
||||
@Result(column = "ratedCop", property = "ratedCop"), |
||||
@Result(column = "copyDate", property = "copyDate") |
||||
}) |
||||
@Select("select * from device_code where project_id=#{projectID} and device_addr=#{deviceAddr} ") |
||||
List<ChillerModel> queryChiller(@Param("projectID") String projectID, @Param("device_addr") String deviceAddr); |
||||
|
||||
} |
@ -1,24 +1,24 @@
|
||||
package com.mh.user.mapper; |
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper; |
||||
import com.mh.user.entity.StrategyInfoEntity; |
||||
import com.mh.user.mapper.provider.DeviceInfoProvider; |
||||
import com.mh.user.mapper.provider.StrategyInfoProvider; |
||||
import org.apache.ibatis.annotations.*; |
||||
|
||||
import java.util.List; |
||||
|
||||
@Mapper |
||||
public interface StrategyInfoMapper { |
||||
public interface StrategyInfoMapper extends BaseMapper<StrategyInfoEntity> { |
||||
|
||||
//查询仪表信息
|
||||
@SelectProvider(type = StrategyInfoProvider.class,method = "queryStrategyInfo") |
||||
@Results(value = { |
||||
@Result(property="id",column="id"), |
||||
@Result(property="dataAnalysis",column="dataAnalysis"), |
||||
@Result(property="operationOpt",column="operation_opt"), |
||||
@Result(property="controlOpt",column="control_opt"), |
||||
@Result(property="projectID",column="project_id"), |
||||
@Result(property="systemID",column="system_id") |
||||
}) |
||||
@Select("<script>" + |
||||
"select * from strategy_info where 1=1 " + |
||||
"<if test='systemID != null and systemID != \"\"'>" + |
||||
" and system_id = #{systemID} " + |
||||
"</if>" + |
||||
"<if test='projectID != null and projectID != \"\"'>" + |
||||
" and project_id = #{projectID} " + |
||||
"</if>" + |
||||
" order by id " + |
||||
"</script>") |
||||
List<StrategyInfoEntity> queryStrategyInfo(@Param("systemID") String systemID,@Param("projectID") String projectID); |
||||
} |
||||
|
@ -1,21 +0,0 @@
|
||||
package com.mh.user.mapper.provider; |
||||
|
||||
|
||||
public class StrategyInfoProvider { |
||||
|
||||
public String queryStrategyInfo(String systemID,String projectID){ |
||||
StringBuffer sql = new StringBuffer(""); |
||||
sql.append("select * from (" + |
||||
" select *,ROW_NUMBER() over(order by id) as rn from strategy_info " + |
||||
" where 1=1 "); |
||||
if (systemID != null && !systemID.equals("")){ |
||||
sql.append(" AND system_id = #{systemID} "); |
||||
} |
||||
if (projectID != null && !projectID.equals("")){ |
||||
sql.append(" AND project_id = #{projectID} "); |
||||
} |
||||
sql.append(" ) T "); |
||||
System.out.println(sql.toString()); |
||||
return sql.toString(); |
||||
} |
||||
} |
@ -1,95 +0,0 @@
|
||||
//package com.mh.user.netty;
|
||||
//
|
||||
//import io.netty.bootstrap.Bootstrap;
|
||||
//import io.netty.channel.*;
|
||||
//import io.netty.channel.nio.NioEventLoopGroup;
|
||||
//import io.netty.channel.socket.SocketChannel;
|
||||
//import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
//import io.netty.handler.timeout.IdleStateHandler;
|
||||
//import io.netty.handler.timeout.ReadTimeoutHandler;
|
||||
//import io.netty.handler.timeout.WriteTimeoutHandler;
|
||||
//import lombok.Getter;
|
||||
//import lombok.Setter;
|
||||
//import lombok.extern.slf4j.Slf4j;
|
||||
//
|
||||
//import java.util.concurrent.TimeUnit;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title :
|
||||
// * @description :Netty冷水机组客户端
|
||||
// * @updateTime 2020-05-13
|
||||
// * @throws :
|
||||
// */
|
||||
//@Slf4j
|
||||
//@Setter
|
||||
//@Getter
|
||||
//public class NettyChillerClient {
|
||||
//
|
||||
// private volatile static NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient();
|
||||
//
|
||||
// private int port;
|
||||
// private String host;
|
||||
//
|
||||
// // 构造函数传递值 继承Thread时需要
|
||||
//// public NettyClient(int port, String host) {
|
||||
//// this.port = port;
|
||||
//// this.host = host;
|
||||
//// }
|
||||
//
|
||||
// public static void connect(int port, String host) throws InterruptedException {
|
||||
// // 配置客户端NIO线程组
|
||||
// EventLoopGroup group = new NioEventLoopGroup(1);
|
||||
// try {
|
||||
// Bootstrap bootstrap = new Bootstrap();
|
||||
// bootstrap.group(group).channel(NioSocketChannel.class)
|
||||
// .option(ChannelOption.TCP_NODELAY, true)
|
||||
// .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
|
||||
// .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024))
|
||||
// .handler(new ChannelInitializer<SocketChannel>() {
|
||||
// @Override
|
||||
// protected void initChannel(SocketChannel socketChannel) {
|
||||
// // 基于换行符号
|
||||
//// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
|
||||
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
//// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
|
||||
//// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
//// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
|
||||
//// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
|
||||
// socketChannel.pipeline().addLast(new IdleStateHandler(10,10,10, TimeUnit.SECONDS));
|
||||
// // 在管道中添加我们自己的接收数据实现方法
|
||||
// socketChannel.pipeline().addLast(new NettyChillerClientHandler());
|
||||
//// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
|
||||
// }
|
||||
// });
|
||||
// // 发起异步连接操作
|
||||
// ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
|
||||
// if (channelFuture.isSuccess()) {
|
||||
// log.info("connect server 成功---------");
|
||||
// } else {
|
||||
// log.info("连接失败!");
|
||||
// log.info("准备重连!");
|
||||
//// connect(port, host);
|
||||
// }
|
||||
//
|
||||
// // 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
|
||||
// channelFuture.channel().closeFuture().sync();
|
||||
// } catch (Exception e) {
|
||||
// log.error("error>>>>>>" + e.getMessage());
|
||||
// } finally {
|
||||
// group.shutdownGracefully();
|
||||
//// try {
|
||||
//// TimeUnit.SECONDS.sleep(5);
|
||||
//// connect(port, host); // 断线重连
|
||||
//// } catch (InterruptedException e) {
|
||||
//// e.printStackTrace();
|
||||
//// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//// @SneakyThrows
|
||||
//// @Override
|
||||
//// public void run() {
|
||||
//// connect(port, host);
|
||||
//// }
|
||||
//}
|
@ -1,315 +0,0 @@
|
||||
//package com.mh.user.netty;
|
||||
//
|
||||
//import com.mh.user.constants.Constant;
|
||||
//import com.mh.user.entity.ChillersEntity;
|
||||
//import com.mh.user.entity.DeviceCodeParamEntity;
|
||||
//import com.mh.user.service.DeviceCodeParamService;
|
||||
//import com.mh.user.service.chillers.ChillersService;
|
||||
//import com.mh.user.service.chillers.GatewayManageService;
|
||||
//import com.mh.user.utils.AnalysisReceiveOrder485;
|
||||
//import com.mh.user.utils.ExchangeStringUtil;
|
||||
//import com.mh.user.utils.GetReadOrder485;
|
||||
//import com.mh.user.utils.SpringBeanUtil;
|
||||
//import io.netty.buffer.ByteBuf;
|
||||
//import io.netty.channel.Channel;
|
||||
//import io.netty.channel.ChannelHandlerAdapter;
|
||||
//import io.netty.channel.ChannelHandlerContext;
|
||||
//import io.netty.handler.timeout.IdleState;
|
||||
//import io.netty.handler.timeout.IdleStateEvent;
|
||||
//import io.netty.util.ReferenceCountUtil;
|
||||
//import lombok.extern.slf4j.Slf4j;
|
||||
//import org.springframework.context.ApplicationContext;
|
||||
//
|
||||
//import java.text.SimpleDateFormat;
|
||||
//import java.util.Date;
|
||||
//import java.util.List;
|
||||
//
|
||||
///**
|
||||
// * @author ljf
|
||||
// * @title :
|
||||
// * @description :客户端异步消息处理机制,采集冷水机组
|
||||
// * @updateTime 2020-05-13
|
||||
// * @throws :
|
||||
// */
|
||||
//@Slf4j
|
||||
//public class NettyChillerClientHandler extends ChannelHandlerAdapter {
|
||||
//
|
||||
// private int num = 0;
|
||||
// private int size = 0;
|
||||
// private int idle_count = 0;
|
||||
// private String receiveStr = "";
|
||||
// List<DeviceCodeParamEntity> deviceCodeParamList;
|
||||
//
|
||||
// // 调用service
|
||||
// ApplicationContext context = SpringBeanUtil.getApplicationContext();
|
||||
// DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class);
|
||||
// GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class);
|
||||
//
|
||||
// /**
|
||||
// * 超时处理
|
||||
// * 如果120秒没有接受客户端的心跳,就触发;
|
||||
// * 如果超过3次,则直接关闭;
|
||||
// */
|
||||
// @Override
|
||||
// public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
|
||||
// if (obj instanceof IdleStateEvent) {
|
||||
// IdleStateEvent event = (IdleStateEvent) obj;
|
||||
// if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
|
||||
// System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据");
|
||||
// if (deviceCodeParamList.get(num) == null) {
|
||||
// System.out.println("关闭这个不活跃的channel");
|
||||
// ctx.channel().close();
|
||||
// } else {
|
||||
// if ((num > size - 1) || (idle_count > 3)) {
|
||||
// System.out.println("关闭这个不活跃的channel");
|
||||
// ctx.channel().close();
|
||||
// }
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
|
||||
// ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr));
|
||||
// idle_count++;
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// super.userEventTriggered(ctx, obj);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
|
||||
// log.info("当前channel从EventLoop取消注册");
|
||||
// ctx.close();
|
||||
// super.channelUnregistered(ctx);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
||||
//// super.exceptionCaught(ctx, cause);
|
||||
// log.info("通信异常!!");
|
||||
//// // 发送采集冷水机组指令
|
||||
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
|
||||
//// // 获取采集参数个数
|
||||
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
//// // 2.发送数据
|
||||
//// ctx.channel().writeAndFlush(buffer);
|
||||
//// receiveStr = null;
|
||||
// cause.printStackTrace();
|
||||
// ctx.close();
|
||||
//// Channel incoming = ctx.channel();
|
||||
//// if (incoming.isActive()) {
|
||||
//// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
|
||||
//// cause.printStackTrace();
|
||||
//// ctx.close();
|
||||
//// receiveStr = null;
|
||||
//// try {
|
||||
//// TimeUnit.SECONDS.sleep(5);
|
||||
//// SocketAddress remoteAddress = ctx.channel().remoteAddress();
|
||||
//// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
|
||||
//// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
|
||||
//// NettyClient nettyClient = new NettyClient();
|
||||
//// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
|
||||
//// } catch (InterruptedException e) {
|
||||
//// e.printStackTrace();
|
||||
//// }
|
||||
//// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// @Override
|
||||
// public void channelActive(ChannelHandlerContext ctx) throws Exception {
|
||||
// super.channelActive(ctx);
|
||||
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
// if (Constant.WEB_FLAG) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
// } else {
|
||||
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
|
||||
// Date date = new Date();
|
||||
// log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!");
|
||||
// // 截取IP地址
|
||||
// String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":");
|
||||
// // 截取端口号
|
||||
// String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", "");
|
||||
// log.info("IP: " + IP + ",端口号: " + port);
|
||||
// // 更新对应的网关在线情况
|
||||
// gatewayManageService.updateGatewayManage(IP, port);
|
||||
// // 生成采集指令
|
||||
// deviceCodeParamList = deviceCodeParamService.queryCodeParam(port);
|
||||
// size = deviceCodeParamList.size();
|
||||
//
|
||||
// // 发送采集冷水机组指令
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
|
||||
// // 获取采集参数个数
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
|
||||
// // byte类型的数据
|
||||
//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
|
||||
//// String sendStr = "5803004900021914"; // 冷量计
|
||||
// // 申请一个数据结构存储信息
|
||||
// ByteBuf buffer = ctx.alloc().buffer();
|
||||
// // 将信息放入数据结构中
|
||||
// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
|
||||
// return buffer;
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void channelInactive(ChannelHandlerContext ctx) throws Exception {
|
||||
// Thread.sleep(100);
|
||||
// ctx.close();
|
||||
// log.info(ctx.channel().localAddress() + "退出链接!!");
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||
// try {
|
||||
// ByteBuf buf = (ByteBuf) msg;
|
||||
// byte[] bytes = new byte[buf.readableBytes()];
|
||||
// buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
// buf.clear();
|
||||
// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
|
||||
// if (bytes.length <= 36) {
|
||||
//// receiveStr = receiveStr.replace("null", "");
|
||||
//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// e.printStackTrace();
|
||||
// } finally {
|
||||
// ReferenceCountUtil.release(msg);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
|
||||
// log.info("冷水机组--数据读取接收完成: " + receiveStr);
|
||||
// if (receiveStr.length() == 30) {
|
||||
// log.info("采集完整的报文: " + receiveStr);
|
||||
// // 解析采集的报文,并保存到数据库
|
||||
// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
|
||||
// analysisReceiveOrder485.analysisChillerOrder485(receiveStr,deviceCodeParamList.get(num));
|
||||
// // 清空receiveStr
|
||||
// receiveStr = "";
|
||||
// // 判断发送的下标,如果不等于指令数组大小
|
||||
// num = num + 1;
|
||||
// if (num > size - 1) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
//// // 继续发送下一个采集冷水机设备指令
|
||||
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
|
||||
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
//// // 发送数据
|
||||
//// ctx.channel().writeAndFlush(buffer);
|
||||
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// } else {
|
||||
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
// if (Constant.WEB_FLAG) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
// } else {
|
||||
// Thread.sleep(1000);
|
||||
// // 继续发送下一个采集冷水机设备指令
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// }
|
||||
// }
|
||||
// } else if (receiveStr.length() == 32) {
|
||||
// log.info("采集完整的报文: " + receiveStr);
|
||||
// // 解析采集的报文,并保存到数据库
|
||||
// AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485();
|
||||
// analysisReceiveOrder485.analysisChillerOrder485(receiveStr,deviceCodeParamList.get(num));
|
||||
// // 清空receiveStr
|
||||
// receiveStr = "";
|
||||
// // 判断发送的下标,如果不等于指令数组大小
|
||||
// num = num + 1;
|
||||
// if (num > size - 1) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
//// // 继续发送下一个采集冷水机设备指令
|
||||
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
|
||||
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
//// // 发送数据
|
||||
//// ctx.channel().writeAndFlush(buffer);
|
||||
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// } else {
|
||||
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
// if (Constant.WEB_FLAG) {
|
||||
// log.info("有指令下发退出定时采集冷水机组参数");
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
// } else {
|
||||
// Thread.sleep(1000);
|
||||
// // 继续发送下一个采集冷水机设备指令
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 2.发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// }
|
||||
// }
|
||||
// } else if (receiveStr.length() > 36) {
|
||||
// // 清空receiveStr
|
||||
// receiveStr = null;
|
||||
// // 判断发送的下标,如果不等于指令数组大小
|
||||
// num = num + 1;
|
||||
// if (num > size - 1) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
//// // 继续发送下一个采集冷水机设备指令
|
||||
//// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
//// String sendStr = getReadOrder485.createChillersOrder(chillersEntityList.get(num));
|
||||
//// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
//// // 发送数据
|
||||
//// ctx.channel().writeAndFlush(buffer);
|
||||
//// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// } else {
|
||||
// // 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
// if (Constant.WEB_FLAG) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// ctx.close();
|
||||
// } else {
|
||||
// Thread.sleep(1000);
|
||||
// // 继续发送下一个采集冷水机设备指令
|
||||
// GetReadOrder485 getReadOrder485 = new GetReadOrder485();
|
||||
// String sendStr = getReadOrder485.createChillersOrder(deviceCodeParamList.get(num));
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// log.info("客户端再次往服务端发送数据" + num + " 数据条数:" + size);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// ctx.flush();
|
||||
// }
|
||||
//
|
||||
//}
|
@ -1,98 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.entity.OrderMessageEntity; |
||||
import io.netty.bootstrap.Bootstrap; |
||||
import io.netty.channel.*; |
||||
import io.netty.channel.nio.NioEventLoopGroup; |
||||
import io.netty.channel.socket.SocketChannel; |
||||
import io.netty.channel.socket.nio.NioSocketChannel; |
||||
import io.netty.handler.timeout.IdleStateHandler; |
||||
import io.netty.handler.timeout.ReadTimeoutHandler; |
||||
import lombok.Getter; |
||||
import lombok.Setter; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
|
||||
import java.util.List; |
||||
import java.util.concurrent.TimeUnit; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description : 控制冷水机组和其他设备 |
||||
* @updateTime 2020-05-28 |
||||
* @throws : |
||||
*/ |
||||
@Setter |
||||
@Getter |
||||
@Slf4j |
||||
public class NettyChillerControlClient { |
||||
|
||||
// private int port;
|
||||
// private String host;
|
||||
// private List<OrderMessageEntity> orderMessageEntityList;
|
||||
|
||||
// 构造函数传递值 继承Thread时需要
|
||||
// public NettyChillerControlClient(int port, String host) {
|
||||
// this.port = port;
|
||||
// this.host = host;
|
||||
// }
|
||||
|
||||
public void connect(int port, String host, List<OrderMessageEntity> orderMessageEntityList) throws InterruptedException { |
||||
// 配置客户端NIO线程组
|
||||
EventLoopGroup group = new NioEventLoopGroup(1); |
||||
try { |
||||
Bootstrap bootstrap = new Bootstrap(); |
||||
bootstrap.group(group).channel(NioSocketChannel.class) |
||||
.option(ChannelOption.TCP_NODELAY, true) |
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) |
||||
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024)) |
||||
.handler(new ChannelInitializer<SocketChannel>() { |
||||
@Override |
||||
protected void initChannel(SocketChannel socketChannel) { |
||||
// 基于换行符号
|
||||
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
|
||||
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
|
||||
// 超过10秒钟没有数据读取自动断开连接
|
||||
// socketChannel.pipeline().addLast(new ReadTimeoutHandler(30));
|
||||
// 超过10秒没有返回触发心跳机制 update by ljf on 2021-01-30
|
||||
socketChannel.pipeline().addLast(new IdleStateHandler(10,10,6, TimeUnit.SECONDS)); |
||||
// 在管道中添加我们自己的接收数据实现方法
|
||||
socketChannel.pipeline().addLast(new NettyChillerControlHandler(orderMessageEntityList)); |
||||
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
|
||||
} |
||||
}); |
||||
// 发起异步连接操作
|
||||
ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); |
||||
if (channelFuture.isSuccess()) { |
||||
log.info("connect server 成功---------"); |
||||
} else { |
||||
log.info("连接失败!"); |
||||
log.info("准备重连!"); |
||||
// connect(port, host);
|
||||
} |
||||
|
||||
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
|
||||
channelFuture.channel().closeFuture().sync(); |
||||
} catch (Exception e) { |
||||
log.error(e.getMessage()); |
||||
} finally { |
||||
group.shutdownGracefully(); |
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// connect(port, host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
|
||||
// @SneakyThrows
|
||||
// @Override
|
||||
// public void run() {
|
||||
// connect(port, host);
|
||||
// }
|
||||
} |
@ -1,315 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.entity.OrderMessageEntity; |
||||
import com.mh.user.service.chillers.GatewayManageService; |
||||
import com.mh.user.service.chillers.OrderMessageService; |
||||
import com.mh.user.utils.AnalysisReceiveOrder485; |
||||
import com.mh.user.constants.Constant; |
||||
import com.mh.user.utils.ExchangeStringUtil; |
||||
import com.mh.user.utils.GetReadOrder485; |
||||
import com.mh.user.utils.SpringBeanUtil; |
||||
import io.netty.buffer.ByteBuf; |
||||
import io.netty.channel.Channel; |
||||
import io.netty.channel.ChannelHandlerAdapter; |
||||
import io.netty.channel.ChannelHandlerContext; |
||||
import io.netty.handler.timeout.IdleState; |
||||
import io.netty.handler.timeout.IdleStateEvent; |
||||
import io.netty.util.ReferenceCountUtil; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.context.ApplicationContext; |
||||
|
||||
import java.text.SimpleDateFormat; |
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :客户端异步消息处理机制 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
public class NettyChillerControlHandler extends ChannelHandlerAdapter { |
||||
|
||||
private int num = 0; |
||||
private int size = 0; |
||||
private String receiveStr = ""; |
||||
private int sendNum = 0; |
||||
private int idle_count = 1; |
||||
|
||||
List<OrderMessageEntity> orderMessageEntityList; |
||||
|
||||
// 调用service
|
||||
ApplicationContext context = SpringBeanUtil.getApplicationContext(); |
||||
GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class); |
||||
OrderMessageService orderMessageService = context.getBean(OrderMessageService.class); |
||||
|
||||
public NettyChillerControlHandler(List<OrderMessageEntity> orderMessageEntityList) { |
||||
this.orderMessageEntityList = orderMessageEntityList; |
||||
} |
||||
|
||||
@Override |
||||
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("当前channel从EventLoop取消注册"); |
||||
// Constant.SEND_STATUS = false;
|
||||
// super.channelUnregistered(ctx);
|
||||
ctx.close(); |
||||
} |
||||
|
||||
/** |
||||
* 超时处理 |
||||
* 如果120秒没有接受客户端的心跳,就触发; |
||||
* 如果超过3次,则直接关闭; |
||||
*/ |
||||
@Override |
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception { |
||||
if (obj instanceof IdleStateEvent) { |
||||
IdleStateEvent event = (IdleStateEvent) obj; |
||||
if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
|
||||
System.out.println("第" + idle_count + "已经10秒没有接收到服务器的信息了,发送第" + num + "条数据"); |
||||
if (num > size - 1) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
Constant.SEND_STATUS = true; |
||||
System.out.println("关闭这个不活跃的channel"); |
||||
ctx.close(); |
||||
} else if (idle_count > 3) { |
||||
System.out.println("关闭这个不活跃的channel"); |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
Constant.SEND_STATUS = false; |
||||
ctx.close(); |
||||
} else { |
||||
// 发送采集DDC指令
|
||||
// 判断空值
|
||||
if (orderMessageEntityList.get(num).getRegisterAddr() == null || |
||||
orderMessageEntityList.get(num).getRegisterAddr().equalsIgnoreCase("")) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
Constant.SEND_STATUS = true; |
||||
ctx.close(); |
||||
} else { |
||||
String sendStr = orderMessageEntityList.get(num).getOrderStr(); |
||||
// // 获取采集参数个数
|
||||
// size = orderMessageEntityList.size();
|
||||
// 2.发送数据
|
||||
ByteBuf buffer = getByteBuf(ctx, sendStr); |
||||
ctx.channel().writeAndFlush(buffer); |
||||
idle_count++; |
||||
} |
||||
} |
||||
} |
||||
} else { |
||||
super.userEventTriggered(ctx, obj); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
||||
// super.exceptionCaught(ctx, cause);
|
||||
log.info("通信异常!!"); |
||||
cause.printStackTrace(); |
||||
// receiveStr = null;
|
||||
// Channel incoming = ctx.channel();
|
||||
// if (incoming.isActive()) {
|
||||
// // 重新发送
|
||||
// if (sendNum > 2) {
|
||||
// // 通信异常,发送失败
|
||||
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
|
||||
// cause.printStackTrace();
|
||||
// Constant.SEND_STATUS = false;
|
||||
// ctx.close();
|
||||
// } else {
|
||||
// // 发送采集DDC指令
|
||||
// String sendStr = orderMessageEntityList.get(num).getOrderStr();
|
||||
// // 获取采集参数个数
|
||||
// size = orderMessageEntityList.size();
|
||||
// // 2.发送数据
|
||||
// ByteBuf buffer = getByteBuf(ctx,sendStr);
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// sendNum += 1;
|
||||
// }
|
||||
// }
|
||||
// // 判断发送的下标,如果不等于指令数组大小
|
||||
// num = num + 1;
|
||||
// if (num > size-1) {
|
||||
// num = 0;
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// Constant.SEND_STATUS = true;
|
||||
// ctx.close();
|
||||
// }
|
||||
} |
||||
|
||||
|
||||
@Override |
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception { |
||||
super.channelActive(ctx); |
||||
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); |
||||
Date date=new Date(); |
||||
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!"); |
||||
// 截取IP地址
|
||||
String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"","/", ":"); |
||||
// 截取端口号
|
||||
String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress()+"",":", ""); |
||||
log.info("IP: " + IP + ",端口号: " + port); |
||||
// 更新对应的网关在线情况
|
||||
gatewayManageService.updateGatewayManage(IP, port); |
||||
|
||||
// 发送控制DDC指令
|
||||
String sendStr = orderMessageEntityList.get(num).getOrderStr(); |
||||
// 获取采集参数个数
|
||||
size = orderMessageEntityList.size(); |
||||
|
||||
// 2.发送数据
|
||||
ByteBuf buffer = getByteBuf(ctx,sendStr); |
||||
ctx.channel().writeAndFlush(buffer); |
||||
} |
||||
|
||||
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { |
||||
// 申请一个数据结构存储信息
|
||||
ByteBuf buffer = ctx.alloc().buffer(); |
||||
// 将信息放入数据结构中
|
||||
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
|
||||
return buffer; |
||||
} |
||||
|
||||
@Override |
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
||||
// Thread.sleep(100);
|
||||
ctx.close(); |
||||
log.info(ctx.channel().localAddress() + "退出链接!!"); |
||||
} |
||||
|
||||
@Override |
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
||||
// super.channelRead(ctx, msg);
|
||||
// ByteBuf buf = (ByteBuf)msg;
|
||||
// byte[] req = new byte[buf.readableBytes()];
|
||||
// buf.readBytes(req);
|
||||
// String body = new String(req, "UTF-8");
|
||||
try { |
||||
ByteBuf buf = (ByteBuf)msg; |
||||
byte [] bytes = new byte[buf.readableBytes()]; |
||||
buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
buf.clear(); |
||||
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes)); |
||||
// if (bytes.length <= 24) {
|
||||
if (bytes.length != 0) { |
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
receiveStr = receiveStr.replace("null", ""); |
||||
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length()); |
||||
} |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
} finally { |
||||
ReferenceCountUtil.release(msg); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("数据读取接收完成: " + receiveStr); |
||||
if (receiveStr.length() == 24) { |
||||
if (receiveStr.equalsIgnoreCase(orderMessageEntityList.get(num).getOrderStr())) { |
||||
// 解析采集回来的数据
|
||||
log.info("采集完整的报文: " + receiveStr + ",指令下标: " + size); |
||||
// 解析采集的报文
|
||||
// 更新发送后的指令
|
||||
OrderMessageEntity orderMessageEntity = new OrderMessageEntity(); |
||||
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr()); |
||||
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime()); |
||||
orderMessageEntity.setGrade(1); |
||||
orderMessageEntity.setSendNum(1); |
||||
orderMessageEntity.setStatus(1); |
||||
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr()); |
||||
orderMessageService.updateOrderMessage(orderMessageEntity); |
||||
|
||||
// // 关闭连接
|
||||
// receiveStr = null;
|
||||
// Constant.SEND_STATUS = true;
|
||||
// ctx.close();
|
||||
|
||||
// 清空receiveStr
|
||||
receiveStr = ""; |
||||
// 判断发送的下标,如果不等于指令数组大小
|
||||
num = num + 1; |
||||
if (num > size - 1) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
Constant.SEND_STATUS = true; |
||||
ctx.close(); |
||||
} else { |
||||
Thread.sleep(4000); |
||||
// 继续发送下一个采集DDC设备指令
|
||||
String sendStr = orderMessageEntityList.get(num).getOrderStr(); |
||||
ByteBuf buffer = getByteBuf(ctx, sendStr); |
||||
// 2.发送数据
|
||||
ctx.channel().writeAndFlush(buffer); |
||||
log.info("客户端再次往服务端发送数据" + num + ",报文: " + sendStr); |
||||
} |
||||
} |
||||
} else if ((receiveStr.length() > 24) && (num == 0)) { |
||||
// 发送采集DDC指令
|
||||
String sendStr = orderMessageEntityList.get(num).getOrderStr(); |
||||
// 获取采集参数个数
|
||||
size = orderMessageEntityList.size(); |
||||
// 2.发送数据
|
||||
ByteBuf buffer = getByteBuf(ctx,sendStr); |
||||
ctx.channel().writeAndFlush(buffer); |
||||
// 清空receiveStr
|
||||
receiveStr = ""; |
||||
sendNum += 1; |
||||
} else if (sendNum > 2){ |
||||
// 更新发送后的指令
|
||||
OrderMessageEntity orderMessageEntity = new OrderMessageEntity(); |
||||
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr()); |
||||
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime()); |
||||
orderMessageEntity.setGrade(1); |
||||
orderMessageEntity.setSendNum(sendNum); |
||||
orderMessageEntity.setStatus(0); |
||||
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr()); |
||||
orderMessageService.updateOrderMessage(orderMessageEntity); |
||||
Constant.SEND_STATUS = false; |
||||
ctx.close(); |
||||
} else if ((receiveStr.length() > 24)) { |
||||
// 接收采集DDC的数据
|
||||
// 解析采集的报文
|
||||
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); |
||||
analysisReceiveOrder485.analysisChillersDDC(receiveStr); |
||||
|
||||
// 清空receiveStr
|
||||
receiveStr = ""; |
||||
// 更新发送后的指令
|
||||
OrderMessageEntity orderMessageEntity = new OrderMessageEntity(); |
||||
orderMessageEntity.setRegisterAddr(orderMessageEntityList.get(num).getRegisterAddr()); |
||||
orderMessageEntity.setCreateTime(orderMessageEntityList.get(num).getCreateTime()); |
||||
orderMessageEntity.setGrade(1); |
||||
orderMessageEntity.setSendNum(1); |
||||
orderMessageEntity.setStatus(1); |
||||
orderMessageEntity.setOrderStr(orderMessageEntityList.get(num).getOrderStr()); |
||||
orderMessageService.updateOrderMessage(orderMessageEntity); |
||||
|
||||
// 判断发送的下标,如果不等于指令数组大小
|
||||
num = num + 1; |
||||
// Thread.sleep(500);
|
||||
if (num > size-1) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
Constant.SEND_STATUS = true; |
||||
ctx.close(); |
||||
} |
||||
} |
||||
ctx.flush(); |
||||
} |
||||
|
||||
} |
@ -1,96 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import io.netty.bootstrap.Bootstrap; |
||||
import io.netty.channel.*; |
||||
import io.netty.channel.nio.NioEventLoopGroup; |
||||
import io.netty.channel.socket.SocketChannel; |
||||
import io.netty.channel.socket.nio.NioSocketChannel; |
||||
import io.netty.handler.timeout.IdleStateHandler; |
||||
import io.netty.handler.timeout.ReadTimeoutHandler; |
||||
import lombok.Getter; |
||||
import lombok.Setter; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
|
||||
import java.util.concurrent.TimeUnit; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :Netty客户端,采集DDC设备数据 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
@Setter |
||||
@Getter |
||||
public class NettyChillerDDCClient { |
||||
|
||||
private volatile static NettyChillerDDCClient nettyChillerDDCClient = new NettyChillerDDCClient(); |
||||
|
||||
private int port; |
||||
private String host; |
||||
|
||||
// 构造函数传递值 继承Thread时需要
|
||||
// public NettyClient(int port, String host) {
|
||||
// this.port = port;
|
||||
// this.host = host;
|
||||
// }
|
||||
|
||||
public static void connect(int port, String host) throws InterruptedException { |
||||
// 配置客户端NIO线程组
|
||||
EventLoopGroup group = new NioEventLoopGroup(1); |
||||
try { |
||||
Bootstrap bootstrap = new Bootstrap(); |
||||
bootstrap.group(group).channel(NioSocketChannel.class) |
||||
.option(ChannelOption.TCP_NODELAY, true) |
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) |
||||
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024)) |
||||
.handler(new ChannelInitializer<SocketChannel>() { |
||||
@Override |
||||
protected void initChannel(SocketChannel socketChannel) { |
||||
// 基于换行符号
|
||||
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
|
||||
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
|
||||
// 超过10秒钟没有数据读取自动断开连接
|
||||
// socketChannel.pipeline().addLast(new ReadTimeoutHandler(40));
|
||||
socketChannel.pipeline().addLast(new IdleStateHandler(20,20,20, TimeUnit.SECONDS)); |
||||
// 在管道中添加我们自己的接收数据实现方法
|
||||
socketChannel.pipeline().addLast(new NettyChillerDDCClientHandler()); |
||||
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
|
||||
} |
||||
}); |
||||
// 发起异步连接操作
|
||||
ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); |
||||
if (channelFuture.isSuccess()) { |
||||
log.info("connect server 成功---------"); |
||||
} else { |
||||
log.info("连接失败!"); |
||||
log.info("准备重连!"); |
||||
// connect(port, host);
|
||||
} |
||||
|
||||
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
|
||||
channelFuture.channel().closeFuture().sync(); |
||||
} catch (Exception e) { |
||||
log.error(e.getMessage()); |
||||
} finally { |
||||
group.shutdownGracefully(); |
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// connect(port, host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
|
||||
// @SneakyThrows
|
||||
// @Override
|
||||
// public void run() {
|
||||
// connect(port, host);
|
||||
// }
|
||||
} |
@ -1,297 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.constants.Constant; |
||||
import com.mh.user.entity.ChillersEntity; |
||||
import com.mh.user.service.chillers.ChillersService; |
||||
import com.mh.user.service.chillers.GatewayManageService; |
||||
import com.mh.user.utils.AnalysisReceiveOrder485; |
||||
import com.mh.user.utils.ExchangeStringUtil; |
||||
import com.mh.user.utils.GetReadOrder485; |
||||
import com.mh.user.utils.SpringBeanUtil; |
||||
import io.netty.buffer.ByteBuf; |
||||
import io.netty.channel.Channel; |
||||
import io.netty.channel.ChannelHandlerAdapter; |
||||
import io.netty.channel.ChannelHandlerContext; |
||||
import io.netty.handler.timeout.IdleState; |
||||
import io.netty.handler.timeout.IdleStateEvent; |
||||
import io.netty.util.ReferenceCountUtil; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.beans.factory.annotation.Autowired; |
||||
import org.springframework.context.ApplicationContext; |
||||
|
||||
import java.text.SimpleDateFormat; |
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :客户端异步消息处理机制 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
public class NettyChillerDDCClientHandler extends ChannelHandlerAdapter { |
||||
|
||||
private int num = 0; |
||||
private int size = 0; |
||||
private int collectionSize = 0; |
||||
private String receiveStr = null; |
||||
private int idle_count = 0; |
||||
List<ChillersEntity> chillersEntityList; |
||||
List<ChillersEntity> chillersEntityList1; |
||||
|
||||
// 调用service
|
||||
ApplicationContext context = SpringBeanUtil.getApplicationContext(); |
||||
ChillersService chillersService = context.getBean(ChillersService.class); |
||||
GatewayManageService gatewayManageService = context.getBean(GatewayManageService.class); |
||||
|
||||
/** |
||||
* 超时处理 |
||||
* 如果120秒没有接受客户端的心跳,就触发; |
||||
* 如果超过3次,则直接关闭; |
||||
*/ |
||||
@Override |
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception { |
||||
if (obj instanceof IdleStateEvent) { |
||||
IdleStateEvent event = (IdleStateEvent) obj; |
||||
if (IdleState.READER_IDLE.equals(event.state())) { //如果读通道处于空闲状态,说明没有接收到心跳命令
|
||||
System.out.println("第" + idle_count + "已经20秒没有接收到服务器的信息了,发送的第" + num + "条数据"); |
||||
if (chillersEntityList.get(num) == null) { |
||||
ctx.close(); |
||||
} else { |
||||
String sendStr = GetReadOrder485.createDDCOrder(chillersEntityList.get(num)); |
||||
ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr)); |
||||
if ((num > size - 1) || (idle_count > 3)) { |
||||
//System.out.println("关闭这个不活跃的channel");
|
||||
//ctx.close();
|
||||
//继续发送下一个ddc采集指令
|
||||
log.info("当前DDC无返回数据超过三次,DDC为:"+chillersEntityList.get(num).getDdcAddr()); |
||||
if (num >= size - 1){ |
||||
log.info("结束DDC采集,当前DDC=====>>>"+chillersEntityList.get(num).getDdcAddr()); |
||||
ctx.close(); |
||||
}else { |
||||
//下发下一个ddc指令之前清除前面的数据
|
||||
receiveStr = null; |
||||
//String sendStr1 = GetReadOrder485.createDDCOrder(chillersEntityList.get(++num));
|
||||
//ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr1));
|
||||
num++; |
||||
sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num); |
||||
} |
||||
idle_count = 0; |
||||
} |
||||
idle_count++; |
||||
} |
||||
} |
||||
} else { |
||||
super.userEventTriggered(ctx, obj); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("当前channel从EventLoop取消注册"); |
||||
super.channelUnregistered(ctx); |
||||
} |
||||
|
||||
@Override |
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
||||
// super.exceptionCaught(ctx, cause);
|
||||
log.info("通信异常!!"); |
||||
receiveStr = null; |
||||
cause.printStackTrace(); |
||||
ctx.close(); |
||||
// Channel incoming = ctx.channel();
|
||||
// if (incoming.isActive()) {
|
||||
// log.info("SimpleClient: " + incoming.remoteAddress() + "异常");
|
||||
// cause.printStackTrace();
|
||||
// ctx.close();
|
||||
// receiveStr = null;
|
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
|
||||
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
|
||||
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
|
||||
// NettyClient nettyClient = new NettyClient();
|
||||
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
} |
||||
|
||||
|
||||
@Override |
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception { |
||||
super.channelActive(ctx); |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.CONTROL_WEB_FLAG) { |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); |
||||
Date date = new Date(); |
||||
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!"); |
||||
// 截取IP地址
|
||||
String IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":"); |
||||
// 截取端口号
|
||||
String port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", ""); |
||||
log.info("IP: " + IP + ",端口号: " + port); |
||||
// 更新对应的网关在线情况
|
||||
gatewayManageService.updateGatewayManage(IP, port); |
||||
// 生成采集指令
|
||||
chillersEntityList = chillersService.queryChillersDDC(2); |
||||
size = chillersEntityList.size(); |
||||
|
||||
// 发送采集DDC指令
|
||||
String sendStr = GetReadOrder485.createDDCOrder(chillersEntityList.get(num)); |
||||
// 获取采集参数个数,grade=2,代表采集DDC设备所对应的参数
|
||||
chillersEntityList1 = chillersService.queryChillersByOther(2, chillersEntityList.get(num).getDdcAddr()); |
||||
StringBuffer getStr = new StringBuffer(); |
||||
for (int i = 0; i < chillersEntityList1.size(); i++) { |
||||
getStr.append(chillersEntityList1.get(i).getRegisterAddress()); |
||||
// getStr = getStr + chillersEntityList1.get(i).getRegisterAddress();
|
||||
} |
||||
collectionSize = getStr.length() / 2; |
||||
log.info("发送的数据: " + sendStr + ",报文大小: " + collectionSize); |
||||
ByteBuf buffer = getByteBuf(ctx, sendStr); |
||||
// 2.发送数据
|
||||
ctx.channel().writeAndFlush(buffer); |
||||
} |
||||
} |
||||
|
||||
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { |
||||
// byte类型的数据
|
||||
// 申请一个数据结构存储信息
|
||||
ByteBuf buffer = ctx.alloc().buffer(); |
||||
// 将信息放入数据结构中
|
||||
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
|
||||
return buffer; |
||||
} |
||||
|
||||
@Override |
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
||||
Thread.sleep(100); |
||||
ctx.close(); |
||||
log.info(ctx.channel().localAddress() + "退出链接!!"); |
||||
} |
||||
|
||||
@Override |
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
||||
try { |
||||
ByteBuf buf = (ByteBuf) msg; |
||||
byte[] bytes = new byte[buf.readableBytes()]; |
||||
buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
buf.clear(); |
||||
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes)); |
||||
if (bytes.length <= (11 + collectionSize * 3) * 2) { |
||||
// if (bytes.length <= 142) {
|
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
receiveStr = receiveStr.replace("null", ""); |
||||
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length()); |
||||
} |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
} finally { |
||||
ReferenceCountUtil.release(msg); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("接收的数据: " + receiveStr + ",报文大小: " + collectionSize); |
||||
if (receiveStr.length() == (11 + 3 * collectionSize) * 2) { |
||||
// if (receiveStr.length() == 142) {
|
||||
// 解析采集回来的数据
|
||||
log.info("采集完整的报文: " + receiveStr); |
||||
|
||||
if (!Constant.CONTROL_WEB_FLAG) { |
||||
// 解析采集的报文
|
||||
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); |
||||
analysisReceiveOrder485.analysisChillersDDC(receiveStr); |
||||
} |
||||
// 清空receiveStr
|
||||
receiveStr = ""; |
||||
// 判断发送的下标,如果不等于指令数组大小
|
||||
num = num + 1; |
||||
if (num > size - 1) { |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
// // 设置长连接,封装发送 update by ljf on 2021-01-26
|
||||
// sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
|
||||
} else { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.CONTROL_WEB_FLAG) { |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
// 设置长连接,封装发送 update by ljf on 2021-01-26
|
||||
sendDDCOrder(chillersEntityList, chillersEntityList.get(num), ctx, num); |
||||
} |
||||
} |
||||
} else if (receiveStr.length() == 20) { |
||||
// if (receiveStr.length() == 142) {
|
||||
// 解析采集回来的数据
|
||||
log.info("采集完整的报文: " + receiveStr); |
||||
// 清空receiveStr
|
||||
receiveStr = ""; |
||||
// 判断发送的下标,如果不等于指令数组大小
|
||||
num = num + 1; |
||||
if (num > size - 1) { |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
// // 设置长连接,封装发送 update by ljf on 2021-01-26
|
||||
// sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num);
|
||||
} else { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.CONTROL_WEB_FLAG) { |
||||
log.info("有指令下发退出定时采集DDC参数"); |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
// 封装发送
|
||||
sendDDCOrder(chillersEntityList, chillersEntityList.get(num), ctx, num); |
||||
} |
||||
} |
||||
}else if (receiveStr.length() > (11 + 3 * collectionSize) * 2){ |
||||
log.info("当前DDC: "+chillersEntityList.get(num).getDdcAddr()+"长度为: "+receiveStr.length()); |
||||
receiveStr = null; |
||||
//继续后面的DDC采集
|
||||
//String sendStr1 = GetReadOrder485.createDDCOrder(chillersEntityList.get(++num));
|
||||
//ctx.channel().writeAndFlush(ExchangeStringUtil.getByteBuf(ctx, sendStr1));
|
||||
num++; |
||||
sendDDCOrder(chillersEntityList,chillersEntityList.get(num),ctx,num); |
||||
} |
||||
ctx.flush(); |
||||
} |
||||
|
||||
public void sendDDCOrder(List<ChillersEntity> chillersEntityList, |
||||
ChillersEntity chillersEntity, |
||||
ChannelHandlerContext ctx, |
||||
int num) throws InterruptedException { |
||||
Thread.sleep(800); |
||||
// 继续发送下一个采集DDC设备指令
|
||||
String sendStr = GetReadOrder485.createDDCOrder(chillersEntity); |
||||
// 获取采集参数个数,grade=2,代表采集DDC设备所对应的参数
|
||||
chillersEntityList1 = chillersService.queryChillersByOther(2, chillersEntityList.get(num).getDdcAddr()); |
||||
StringBuilder getStr = new StringBuilder(); |
||||
for (ChillersEntity entity : chillersEntityList1) { |
||||
getStr.append(entity.getRegisterAddress()); |
||||
} |
||||
collectionSize = getStr.length() / 2; |
||||
log.info("发送的数据: " + sendStr + ",报文大小: " + collectionSize); |
||||
log.info("客户端再次往服务端发送数据 " + num + "," + sendStr); |
||||
ByteBuf buffer = getByteBuf(ctx, sendStr); |
||||
// 2.发送数据
|
||||
ctx.channel().writeAndFlush(buffer); |
||||
} |
||||
|
||||
} |
@ -1,90 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import io.netty.bootstrap.Bootstrap; |
||||
import io.netty.channel.*; |
||||
import io.netty.channel.nio.NioEventLoopGroup; |
||||
import io.netty.channel.socket.SocketChannel; |
||||
import io.netty.channel.socket.nio.NioSocketChannel; |
||||
import io.netty.handler.timeout.ReadTimeoutHandler; |
||||
import lombok.Getter; |
||||
import lombok.Setter; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :Netty客户端,采集冷量计 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
@Setter |
||||
@Getter |
||||
public class NettyClient { |
||||
|
||||
private int port; |
||||
private String host; |
||||
|
||||
// 构造函数传递值 继承Thread时需要
|
||||
// public NettyClient(int port, String host) {
|
||||
// this.port = port;
|
||||
// this.host = host;
|
||||
// }
|
||||
|
||||
public void connect(int port, String host) throws InterruptedException { |
||||
// 配置客户端NIO线程组
|
||||
EventLoopGroup group = new NioEventLoopGroup(1); |
||||
try { |
||||
Bootstrap bootstrap = new Bootstrap(); |
||||
bootstrap.group(group).channel(NioSocketChannel.class) |
||||
.option(ChannelOption.TCP_NODELAY, true) |
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) |
||||
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024)) |
||||
.handler(new ChannelInitializer<SocketChannel>() { |
||||
@Override |
||||
protected void initChannel(SocketChannel socketChannel) { |
||||
// 基于换行符号
|
||||
// socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4,-8,0));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
|
||||
// socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
|
||||
// 超过10秒钟没有数据读取自动断开连接
|
||||
socketChannel.pipeline().addLast(new ReadTimeoutHandler(10)); |
||||
// 在管道中添加我们自己的接收数据实现方法
|
||||
socketChannel.pipeline().addLast(new NettyClientHandler()); |
||||
// socketChannel.pipeline().addLast(new NettyMeterClientHandler());
|
||||
} |
||||
}); |
||||
// 发起异步连接操作
|
||||
ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); |
||||
if (channelFuture.isSuccess()) { |
||||
log.info("connect server 成功---------"); |
||||
} else { |
||||
log.info("连接失败!"); |
||||
log.info("准备重连!"); |
||||
// connect(port, host);
|
||||
} |
||||
|
||||
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
|
||||
channelFuture.channel().closeFuture().sync(); |
||||
} catch (Exception e) { |
||||
log.error(e.getMessage()); |
||||
} finally { |
||||
group.shutdownGracefully(); |
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// connect(port, host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
|
||||
// @SneakyThrows
|
||||
// @Override
|
||||
// public void run() {
|
||||
// connect(port, host);
|
||||
// }
|
||||
} |
@ -1,190 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.constants.Constant; |
||||
import com.mh.user.entity.DeviceCodeParamEntity; |
||||
import com.mh.user.entity.DeviceManageEntity; |
||||
import com.mh.user.service.DeviceCodeParamService; |
||||
import com.mh.user.service.chillers.DeviceManageService; |
||||
import com.mh.user.utils.*; |
||||
import io.netty.buffer.ByteBuf; |
||||
import io.netty.channel.Channel; |
||||
import io.netty.channel.ChannelHandlerAdapter; |
||||
import io.netty.channel.ChannelHandlerContext; |
||||
import io.netty.util.ReferenceCountUtil; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.context.ApplicationContext; |
||||
|
||||
import java.text.SimpleDateFormat; |
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :客户端异步消息处理机制 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
public class NettyClientHandler extends ChannelHandlerAdapter { |
||||
|
||||
private int num = 0; |
||||
private int size = 0; |
||||
private String receiveStr = null; |
||||
private String IP = null; |
||||
private String port = null; |
||||
List<DeviceCodeParamEntity> deviceManageEntityList; |
||||
|
||||
// 调用service
|
||||
ApplicationContext context = SpringBeanUtil.getApplicationContext(); |
||||
DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class); |
||||
|
||||
|
||||
@Override |
||||
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("当前channel从EventLoop取消注册"); |
||||
super.channelUnregistered(ctx); |
||||
} |
||||
|
||||
@Override |
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
||||
// super.exceptionCaught(ctx, cause);
|
||||
log.info("通信异常!!"); |
||||
receiveStr = null; |
||||
Channel incoming = ctx.channel(); |
||||
if (incoming.isActive()){ |
||||
log.info("SimpleClient: " + incoming.remoteAddress() + "异常"); |
||||
cause.printStackTrace(); |
||||
ctx.close(); |
||||
// receiveStr = null;
|
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
|
||||
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
|
||||
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
|
||||
// NettyClient nettyClient = new NettyClient();
|
||||
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public void channelActive(ChannelHandlerContext ctx) { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.WEB_FLAG) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
ctx.channel().read(); |
||||
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); |
||||
Date date = new Date(); |
||||
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!"); |
||||
// 截取IP地址
|
||||
IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":"); |
||||
// 截取端口号
|
||||
port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", ""); |
||||
log.info("IP: " + IP + ",端口号: " + port); |
||||
// 生成对应采集冷量计的命令
|
||||
deviceManageEntityList = deviceCodeParamService.queryCodeParam(port); |
||||
size = deviceManageEntityList.size(); |
||||
|
||||
// 封装工具类进行采集,update by ljf on 2021-01-26
|
||||
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(0),ctx,num,size); |
||||
} |
||||
|
||||
} |
||||
|
||||
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { |
||||
// byte类型的数据
|
||||
// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
|
||||
// String sendStr = "5803004900021914"; // 冷量计
|
||||
// 申请一个数据结构存储信息
|
||||
ByteBuf buffer = ctx.alloc().buffer(); |
||||
// 将信息放入数据结构中
|
||||
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
|
||||
return buffer; |
||||
} |
||||
|
||||
@Override |
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
||||
Thread.sleep(100); |
||||
ctx.close(); |
||||
log.info(ctx.channel().localAddress() + "退出链接!!"); |
||||
} |
||||
|
||||
@Override |
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
||||
try { |
||||
ByteBuf buf = (ByteBuf)msg; |
||||
byte [] bytes = new byte[buf.readableBytes()]; |
||||
buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
buf.clear(); |
||||
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes)); |
||||
if (bytes.length <= 36) { |
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
receiveStr = receiveStr.replace("null", ""); |
||||
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length()); |
||||
} |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
} finally { |
||||
ReferenceCountUtil.release(msg); |
||||
} |
||||
} |
||||
|
||||
@Override |
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("采集冷量计-数据读取接收完成: " + receiveStr); |
||||
// A9 FE C2 C7 1F 90 01 58 03 04 4A 30 00 53 65 1C C4 06
|
||||
if (receiveStr.length() == 36) { |
||||
// 接收到的报文
|
||||
log.info("接收完整报文: " + receiveStr); |
||||
// 解析报文
|
||||
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); |
||||
analysisReceiveOrder485.analysisCloudOrder485(receiveStr,deviceManageEntityList.get(num)); // 解析冷量计
|
||||
receiveStr = ""; |
||||
// 1.创建将要写出的数据
|
||||
// String sendStr = "5803004900021914";
|
||||
num = num + 1; |
||||
Thread.sleep(500); |
||||
if (num > size-1) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
// 保持长连接
|
||||
// // 封装工具类进行采集,update by ljf on 2021-01-26
|
||||
// SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
|
||||
} else { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.WEB_FLAG) { |
||||
log.info("有指令下发退出定时采集参数"); |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
// 封装工具类进行采集,update by ljf on 2021-01-26
|
||||
SendOrderUtils.sendCloudOrder(deviceManageEntityList.get(num),ctx,num,size); |
||||
} |
||||
} |
||||
|
||||
} else { |
||||
log.info(receiveStr); |
||||
receiveStr = null; |
||||
ctx.flush(); |
||||
ctx.close(); |
||||
} |
||||
|
||||
ctx.flush(); |
||||
} |
||||
|
||||
} |
@ -1,180 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.utils.ExchangeStringUtil; |
||||
import io.netty.bootstrap.ServerBootstrap; |
||||
import io.netty.buffer.ByteBuf; |
||||
import io.netty.buffer.Unpooled; |
||||
import io.netty.channel.*; |
||||
import io.netty.channel.nio.NioEventLoopGroup; |
||||
import io.netty.channel.socket.SocketChannel; |
||||
import io.netty.channel.socket.nio.NioServerSocketChannel; |
||||
import io.netty.handler.logging.LogLevel; |
||||
import io.netty.handler.logging.LoggingHandler; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.util.StringUtils; |
||||
|
||||
import java.io.IOException; |
||||
import java.net.InetSocketAddress; |
||||
|
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title :Netty |
||||
* @description :netty 使用 |
||||
* @updateTime 2020-04-21 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
public class NettyEchoServer { |
||||
|
||||
public void bind(int port) throws Exception { |
||||
// accept线程组,用来接收连接
|
||||
EventLoopGroup bossGroup = new NioEventLoopGroup(1); |
||||
// IO 线程组,用来处理业务逻辑
|
||||
EventLoopGroup workerGroup = new NioEventLoopGroup(1); |
||||
|
||||
try { |
||||
// 服务端启动引导
|
||||
ServerBootstrap serverBootstrap = new ServerBootstrap(); |
||||
serverBootstrap.group(bossGroup,workerGroup) // 绑定两个线程
|
||||
.channel(NioServerSocketChannel.class) // 指定通道类型
|
||||
.option(ChannelOption.SO_BACKLOG, 1024) // 设置TCP连接的缓冲区
|
||||
.handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() { |
||||
@Override |
||||
protected void initChannel(SocketChannel socketChannel) throws Exception { |
||||
ChannelPipeline pipeline = socketChannel.pipeline(); // 获取处理器链
|
||||
pipeline.addLast(new EchoServerHandler()); // 添加新的事件处理器
|
||||
} |
||||
}); |
||||
// 通过bind启动服务
|
||||
ChannelFuture f = serverBootstrap.bind(port).sync(); |
||||
// 阻塞主线程,知道网络服务被关闭
|
||||
f.channel().closeFuture().sync(); |
||||
} catch (Exception e){ |
||||
e.printStackTrace(); |
||||
} finally { |
||||
workerGroup.shutdownGracefully(); |
||||
bossGroup.shutdownGracefully(); |
||||
} |
||||
} |
||||
|
||||
static class EchoServerHandler extends ChannelHandlerAdapter { |
||||
|
||||
// 每当从客户端收到新的数据时,这个方法会在收到消息时被调用
|
||||
@Override |
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
||||
try { |
||||
ByteBuf buf = (ByteBuf)msg; |
||||
byte [] bytes = new byte[buf.readableBytes()]; |
||||
buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
String receiveStr = ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
log.info("接收到的数据: "+ receiveStr); |
||||
|
||||
//返回16进制到客户端
|
||||
writeToClient(receiveStr,ctx,"测试"); |
||||
} catch (Exception e) { |
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace(); |
||||
} |
||||
// ctx.write(Unpooled.wrappedBuffer("Server message".getBytes()));
|
||||
// ctx.fireChannelRead(msg);
|
||||
} |
||||
|
||||
// 数据读取完后被调用
|
||||
@Override |
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { |
||||
ctx.flush(); |
||||
} |
||||
|
||||
// 当Netty由于IO错误或者处理器在处理事件时抛出的异常时被调用
|
||||
@Override |
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
||||
cause.printStackTrace(); |
||||
ctx.close(); |
||||
} |
||||
|
||||
/** |
||||
* 客户端与服务端第一次建立连接时 执行 |
||||
* |
||||
* @param ctx |
||||
* @throws Exception |
||||
*/ |
||||
@Override |
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception, IOException |
||||
{ |
||||
super.channelActive(ctx); |
||||
ctx.channel().read(); |
||||
InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress(); |
||||
String clientIp = ifsock.getAddress().getHostAddress(); |
||||
//此处不能使用ctx.close(),否则客户端始终无法与服务端建立连接
|
||||
log.info("channelActive: "+clientIp + ctx.name()); |
||||
} |
||||
|
||||
/** |
||||
* 客户端与服务端 断连时 执行 |
||||
* |
||||
* @param ctx |
||||
* @throws Exception |
||||
*/ |
||||
@Override |
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception, IOException |
||||
{ |
||||
super.channelInactive(ctx); |
||||
InetSocketAddress ifsock = (InetSocketAddress) ctx.channel().remoteAddress(); |
||||
String clientIp = ifsock.getAddress().getHostAddress(); |
||||
ctx.close(); //断开连接时,必须关闭,否则造成资源浪费,并发量很大情况下可能造成宕机
|
||||
System.out.println("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 ifsock = (InetSocketAddress) ctx.channel().remoteAddress(); |
||||
String clientIp = ifsock.getAddress().getHostAddress(); |
||||
ctx.close();//超时时断开连接
|
||||
System.out.println("userEventTriggered:"+clientIp); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* 公用回写数据到客户端的方法 |
||||
* @param channel |
||||
* @param mark 用于打印/log的输出 |
||||
* <br>//channel.writeAndFlush(msg);//不行
|
||||
* <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
|
||||
* <br>在netty里,进出的都是ByteBuf,楼主应确定服务端是否有对应的编码器,将字符串转化为ByteBuf |
||||
*/ |
||||
private void writeToClient(final String receiveStr, ChannelHandlerContext channel, final String mark) { |
||||
try { |
||||
ByteBuf buff = Unpooled.buffer();//netty需要用ByteBuf传输
|
||||
buff.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(receiveStr));//对接需要16进制
|
||||
channel.writeAndFlush(buff).addListener((ChannelFutureListener) future -> { |
||||
StringBuilder sb = new StringBuilder(""); |
||||
if(!StringUtils.isEmpty(mark)){ |
||||
sb.append("【").append(mark).append("】"); |
||||
} |
||||
if (future.isSuccess()) { |
||||
System.out.println(sb.toString()+"回写成功"+receiveStr); |
||||
log.info(sb.toString()+"回写成功"+receiveStr); |
||||
} else { |
||||
System.out.println(sb.toString()+"回写失败"+receiveStr); |
||||
log.error(sb.toString()+"回写失败"+receiveStr); |
||||
} |
||||
}); |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
System.out.println("调用通用writeToClient()异常"+e.getMessage()); |
||||
log.error("调用通用writeToClient()异常:",e); |
||||
} |
||||
} |
||||
} |
||||
} |
@ -1,95 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import io.netty.bootstrap.Bootstrap; |
||||
import io.netty.channel.*; |
||||
import io.netty.channel.nio.NioEventLoopGroup; |
||||
import io.netty.channel.socket.SocketChannel; |
||||
import io.netty.channel.socket.nio.NioSocketChannel; |
||||
import io.netty.handler.timeout.ReadTimeoutHandler; |
||||
import lombok.Getter; |
||||
import lombok.Setter; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :Netty客户端,采集电表 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
@Setter |
||||
@Getter |
||||
public class NettyMeterClient { |
||||
// implements Runnable {
|
||||
|
||||
private int port; |
||||
private String host; |
||||
|
||||
// 构造函数传递值 继承Thread时需要
|
||||
public NettyMeterClient(int port, String host) { |
||||
this.port = port; |
||||
this.host = host; |
||||
} |
||||
|
||||
public NettyMeterClient() { |
||||
super(); |
||||
} |
||||
|
||||
public void connect(int port, String host) throws InterruptedException { |
||||
// 配置客户端NIO线程组
|
||||
// 配置客户端NIO线程组
|
||||
EventLoopGroup group = new NioEventLoopGroup(1); |
||||
try { |
||||
Bootstrap bootstrap = new Bootstrap(); |
||||
bootstrap.group(group).channel(NioSocketChannel.class) |
||||
.option(ChannelOption.TCP_NODELAY, true) |
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) |
||||
.option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(1024*1024)) |
||||
.handler(new ChannelInitializer<SocketChannel>() { |
||||
@Override |
||||
protected void initChannel(SocketChannel socketChannel) { |
||||
// 基于换行符号
|
||||
// socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringDecoder(StandardCharsets.UTF_8));
|
||||
// // 解码转String,注意调整自己的编码格式GBK、UTF-8
|
||||
// socketChannel.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
|
||||
// 超过10秒钟没有数据读取自动断开连接
|
||||
socketChannel.pipeline().addLast(new ReadTimeoutHandler(20)); |
||||
// 在管道中添加我们自己的接收数据实现方法
|
||||
// socketChannel.pipeline().addLast(new NettyClientHandler());
|
||||
socketChannel.pipeline().addLast(new NettyMeterClientHandler()); |
||||
} |
||||
}); |
||||
// 发起异步连接操作
|
||||
ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); |
||||
if (channelFuture.isSuccess()) { |
||||
log.info("connect server 成功---------"); |
||||
} else { |
||||
log.info("连接失败!"); |
||||
log.info("准备重连!"); |
||||
// connect(port, host);
|
||||
} |
||||
|
||||
// 等待客户端连接链路关闭future.channel().closeFuture().sync(); // 阻塞main线程
|
||||
channelFuture.channel().closeFuture().sync(); |
||||
} catch (Exception e) { |
||||
log.error(e.getMessage()); |
||||
} finally { |
||||
group.shutdownGracefully(); |
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// connect(port, host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
//
|
||||
// @SneakyThrows
|
||||
// @Override
|
||||
// public void run() {
|
||||
// connect(port, host);
|
||||
// }
|
||||
} |
@ -1,261 +0,0 @@
|
||||
package com.mh.user.netty; |
||||
|
||||
import com.mh.user.constants.Constant; |
||||
import com.mh.user.entity.DeviceCodeParamEntity; |
||||
import com.mh.user.entity.DeviceManageEntity; |
||||
import com.mh.user.service.DeviceCodeParamService; |
||||
import com.mh.user.service.chillers.DeviceManageService; |
||||
import com.mh.user.utils.*; |
||||
import io.netty.buffer.ByteBuf; |
||||
import io.netty.channel.Channel; |
||||
import io.netty.channel.ChannelHandlerAdapter; |
||||
import io.netty.channel.ChannelHandlerContext; |
||||
import io.netty.util.ReferenceCountUtil; |
||||
import lombok.extern.slf4j.Slf4j; |
||||
import org.springframework.context.ApplicationContext; |
||||
|
||||
import java.text.SimpleDateFormat; |
||||
import java.util.Date; |
||||
import java.util.List; |
||||
|
||||
/** |
||||
* @author ljf |
||||
* @title : |
||||
* @description :客户端异步消息处理机制 |
||||
* @updateTime 2020-05-13 |
||||
* @throws : |
||||
*/ |
||||
@Slf4j |
||||
public class NettyMeterClientHandler extends ChannelHandlerAdapter { |
||||
|
||||
|
||||
private int num = 0; |
||||
private int size = 0; |
||||
private String receiveStr = null; |
||||
private String IP = ""; |
||||
private String port = ""; |
||||
List<DeviceCodeParamEntity> deviceManageEntityList; |
||||
|
||||
// 调用service
|
||||
ApplicationContext context = SpringBeanUtil.getApplicationContext(); |
||||
DeviceCodeParamService deviceCodeParamService = context.getBean(DeviceCodeParamService.class); |
||||
|
||||
AnalysisReceiveOrder485 analysisReceiveOrder485 = new AnalysisReceiveOrder485(); |
||||
|
||||
@Override |
||||
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("当前channel从EventLoop取消注册"); |
||||
super.channelUnregistered(ctx); |
||||
} |
||||
|
||||
@Override |
||||
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { |
||||
// super.exceptionCaught(ctx, cause);
|
||||
log.info("通信异常!!"); |
||||
// receiveStr = null;
|
||||
Channel incoming = ctx.channel(); |
||||
if (incoming.isActive()) { |
||||
log.info("SimpleClient: " + incoming.remoteAddress() + "异常"); |
||||
receiveStr = null; |
||||
cause.printStackTrace(); |
||||
ctx.close(); |
||||
// receiveStr = null;
|
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(5);
|
||||
// SocketAddress remoteAddress = ctx.channel().remoteAddress();
|
||||
// String port = ExchangeStringUtil.endData(remoteAddress.toString(),":");
|
||||
// String host = ExchangeStringUtil.splitData(remoteAddress.toString(),"/",":");
|
||||
// NettyClient nettyClient = new NettyClient();
|
||||
// nettyClient.connect(Integer.parseInt(port), host); // 断线重连
|
||||
// } catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
} |
||||
} |
||||
|
||||
|
||||
@Override |
||||
public void channelActive(ChannelHandlerContext ctx) throws Exception { |
||||
// super.channelActive(ctx);
|
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.WEB_FLAG) { |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
ctx.channel().read(); |
||||
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); |
||||
Date date = new Date(); |
||||
log.info(ctx.channel().remoteAddress() + " " + sdf1.format(date) + "链接服务端成功!"); |
||||
|
||||
// 截取IP地址
|
||||
IP = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", "/", ":"); |
||||
// 截取端口号
|
||||
port = ExchangeStringUtil.getMidString(ctx.channel().remoteAddress() + "", ":", ""); |
||||
log.info("IP: " + IP + ",端口号: " + port); |
||||
|
||||
// 生成对应的采集指令
|
||||
// 修改生成指令(冷量计和电量一起采集) update by ljf on 2021-01-27
|
||||
deviceManageEntityList = deviceCodeParamService.queryCodeParam(port); |
||||
size = deviceManageEntityList.size(); |
||||
|
||||
log.info("初始连接报文: " + receiveStr); |
||||
receiveStr = ""; |
||||
// 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
|
||||
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(0),ctx,num,size); |
||||
// 1.创建将要写出的数据
|
||||
// String sendStr = "6830043080000068110432326536C816"; // 网络单相电表
|
||||
// String sendStr = "FEFEFEFE6880025007000068010243C3B216"; // 广仪三相电表
|
||||
// String collectionNum = deviceManageEntityList.get(0).getCollectionNum();
|
||||
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
|
||||
// deviceManageEntityList.get(0).getDataCom(), collectionNum, "1");
|
||||
//// FileUtils.createFileAndWrite(sendStr, 0);
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 2.发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
} |
||||
|
||||
} |
||||
|
||||
private ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { |
||||
// byte类型的数据
|
||||
// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
|
||||
// String sendStr = "5803004900021914"; // 冷量计
|
||||
// 申请一个数据结构存储信息
|
||||
ByteBuf buffer = ctx.alloc().buffer(); |
||||
// 将信息放入数据结构中
|
||||
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
|
||||
return buffer; |
||||
} |
||||
|
||||
@Override |
||||
public void channelInactive(ChannelHandlerContext ctx) throws Exception { |
||||
Thread.sleep(500); |
||||
receiveStr = null; |
||||
ctx.close(); |
||||
log.info(ctx.channel().localAddress() + "退出链接!!"); |
||||
} |
||||
|
||||
@Override |
||||
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { |
||||
try { |
||||
ByteBuf buf = (ByteBuf) msg; |
||||
byte[] bytes = new byte[buf.readableBytes()]; |
||||
buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
buf.clear(); |
||||
log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes)); |
||||
if (bytes.length <= 62) { |
||||
// if (bytes.length <= 142) {
|
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
receiveStr = receiveStr.replace("null", ""); |
||||
log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length()); |
||||
} |
||||
} catch (Exception e) { |
||||
e.printStackTrace(); |
||||
} finally { |
||||
ReferenceCountUtil.release(msg); |
||||
} |
||||
// super.channelRead(ctx, msg);
|
||||
// ByteBuf buf = (ByteBuf)msg;
|
||||
// byte[] req = new byte[buf.readableBytes()];
|
||||
// buf.readBytes(req);
|
||||
// String body = new String(req, "UTF-8");
|
||||
// ByteBuf buf = (ByteBuf)msg;
|
||||
// byte [] bytes = new byte[buf.readableBytes()];
|
||||
// buf.readBytes(bytes);//复制内容到字节数组bytes
|
||||
// log.info("获取到的值: " + ExchangeStringUtil.bytesToHexString(bytes));
|
||||
// if (bytes.length != 0) {
|
||||
//// receiveStr = receiveStr.replace("null", "");
|
||||
//// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
//// log.info(ctx.channel().remoteAddress() + " " + ctx.channel().localAddress() + " 接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
// receiveStr = receiveStr + ExchangeStringUtil.bytesToHexString(bytes);//将接收到的数据转为字符串,此字符串就是客户端发送的字符串
|
||||
// receiveStr = receiveStr.replace("null", "");
|
||||
// log.info("接受服务器数据:" + receiveStr + ",大小: " + receiveStr.length());
|
||||
// }
|
||||
} |
||||
|
||||
@Override |
||||
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { |
||||
log.info("采集电表-数据读取接收完成: " + receiveStr); |
||||
// 把receiveStr的"null"值去掉
|
||||
// a9fec2c71f9002fefefefe6839025007000068810643c3bb446c338d16c2b8
|
||||
// A9 FE C2 C7 1F 90 02 FE FE FE FE 68 39 02 50 07 00 00 68 81 06 43 C3 5B 38 6C 33 21 16 F8 12
|
||||
if ((receiveStr.length() == 62)) { |
||||
// log.info(receiveStr);
|
||||
analysisReceiveOrder485.analysisMeterOrder485(receiveStr,deviceManageEntityList.get(num)); // 解析电表
|
||||
receiveStr = ""; |
||||
num = num + 1; |
||||
Thread.sleep(600); |
||||
if (num > size - 1) { |
||||
num = 0; |
||||
receiveStr = null; |
||||
// 关闭连接
|
||||
ctx.close(); |
||||
// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
|
||||
// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
|
||||
} else { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.WEB_FLAG) { |
||||
log.info("有指令下发退出定时采集DDC参数"); |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
// 封装发送电表工具方法 update by ljf on 2021-01-26
|
||||
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),ctx,num,size); |
||||
// 1.创建将要写出的数据
|
||||
// fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
|
||||
// String sendStr = "FEFEFE6880025007000068010243C3B216";
|
||||
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
|
||||
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
|
||||
// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 2.发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// log.info("客户端再次往服务端发送数据" + num);
|
||||
} |
||||
} |
||||
} else if ((receiveStr.length() > 62)) { |
||||
receiveStr = null; |
||||
num = num + 1; |
||||
Thread.sleep(500); |
||||
if (num > size - 1) { |
||||
num = 0; |
||||
receiveStr = null; |
||||
// 关闭连接
|
||||
ctx.close(); |
||||
// // 保持长连接,封装发送电表工具方法 update by ljf on 2021-01-26
|
||||
// SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),num,IP,port,ctx);
|
||||
} else { |
||||
// 添加一个状态值,判断是否继续发送指令 update by ljf on 2020-08-07
|
||||
if (Constant.WEB_FLAG) { |
||||
log.info("有指令下发退出定时采集DDC参数"); |
||||
num = 0; |
||||
// 关闭连接
|
||||
receiveStr = null; |
||||
ctx.close(); |
||||
} else { |
||||
// 封装发送电表工具方法 update by ljf on 2021-01-26
|
||||
SendOrderUtils.sendMeterOrder(deviceManageEntityList.get(num),ctx,num,size); |
||||
// 1.创建将要写出的数据
|
||||
// fe fe fe fe 68 80 02 50 07 00 00 68 81 06 43 c3 8c 34 33 33 5c 16
|
||||
// String sendStr = "FEFEFE6880025007000068010243C3B216";
|
||||
// String collectionNum = deviceManageEntityList.get(num).getCollectionNum();
|
||||
// String sendStr = GetReadOrder485.createMeterOrder(IP, port,
|
||||
// deviceManageEntityList.get(num).getDataCom(), collectionNum, "1");
|
||||
// ByteBuf buffer = getByteBuf(ctx, sendStr);
|
||||
// // 2.发送数据
|
||||
// ctx.channel().writeAndFlush(buffer);
|
||||
// log.info("客户端再次往服务端发送数据" + num);
|
||||
} |
||||
} |
||||
} |
||||
ctx.flush(); |
||||
} |
||||
|
||||
} |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue