工具类:
package com.zg.mymes.myConnPLC.myS7;
import com.github.s7connector.api.DaveArea;
import com.github.s7connector.api.S7Connector;
import com.github.s7connector.api.S7Serializer;
import com.github.s7connector.api.factory.S7ConnectorFactory;
import com.github.s7connector.api.factory.S7SerializerFactory;
import com.zg.mymes.entities.ActualData;
import com.zg.mymes.entities.MyConfig;
import com.zg.mymes.helper.MyJsonConfigTool;
import com.zg.mymes.myConnPLC.DataConvert;
import com.zg.mymes.myConnPLC.myS7.myS7entities.MyS7Entity;
import com.zg.mymes.myConnPLC.myS7.myS7entities.MyS7WriteEntity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
/**
* @Auther: Zg
* @Date: 2022/11/23 - 11 - 23 - 17:14
* @Description: com.zg.mymes.myConnPLC.myS7
* @version: 1.0
*/
@Component
@Slf4j
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class S7ConnHelper implements IS7ConnHelper {
private String Ip;
private Integer Port;
public S7Connector s7Connector;
public S7Serializer s7Serializer;
private List<ActualData> actualDatas = new ArrayList<ActualData>();
private MyS7Entity myDbData;
private List<Object> myDbDataList = new ArrayList<>();
private List<MyS7Entity> myDbDatas = new ArrayList<MyS7Entity>();
private Map<String,Object> myMap = new HashMap<>();
private Integer errorTimes = 0;
private Boolean isConnected = false;
private Boolean heart = false;
@Autowired
private MyJsonConfigTool configTool;
@Autowired
private DataConvert dataConvert;
@Override
public void initConnect() throws IOException {
MyConfig myConfig = configTool.ReadJson();
Ip = myConfig.getIp();
Port = 102;
actualDatas = myConfig.getActualDatas();
if (this.s7Connector==null){
this.s7Connector = S7ConnectorFactory.buildTCPConnector()
.withHost(Ip)
.withPort(Port)
.withTimeout(10000)
.withRack(0)//机架号
.withSlot(1)//插槽号
.build();
this.s7Serializer = S7SerializerFactory.buildSerializer(s7Connector);
this.isConnected = true;
}
}
/**
*
* @param dbNum DB号
* @param clazz 变量
* @param offSet 偏移量
*/
@Override
public MyS7Entity readPlcData(Integer dbNum, Class<?> clazz, int offSet){
//第一个参数:DaveArea.DB 表示读取PLC的地址区域为DB
//第二个参数:DB块地址,若plc中是DB1000,则填1000
//第三个参数:数据长度
//第四个参数:偏移量
//s7Connector.read(DaveArea.DB,)
// this.clazz = clazz;
// this.dbNum = dbNum;
//S7Serializer s7Serializer = S7SerializerFactory.buildSerializer(s7Connector);
//db号,偏移量
if (this.isConnected=true){
// java.util.Date date = new Date();//获得当前时间
// Timestamp t = new Timestamp(date.getTime());
this.myDbData = (MyS7Entity)this.s7Serializer.dispense(clazz, dbNum, offSet);
//this.myDbData.setCreateTime(t);
//心跳
if (heart==false){
this.myDbData.setHeartBeat(10);
heart=true;
}
else if (heart==true){
this.myDbData.setHeartBeat(20);
heart=false;
}
try {
this.s7Serializer.store(this.myDbData,dbNum,offSet);
}
//断线重连
catch (Exception ex){
log.info(ex.getMessage()+"Inner+=+=");
this.isConnected=false;
try {
this.s7Connector.close();
} catch (IOException e) {
e.printStackTrace();
}
this.s7Connector=null;
this.s7Serializer=null;
try {
this.initConnect();
errorTimes=0;
} catch (IOException e) {
e.printStackTrace();
}
}
this.myDbData = (MyS7Entity)this.s7Serializer.dispense(clazz, dbNum, offSet);
if (myDbDatas.size()<30){
myDbDatas.add(myDbData);
}
else {
myDbDatas.remove(0);
}
}
return myDbData;
}
@Override
public MyS7Entity readTheDbData(Integer dbNum, MyS7Entity clazz, int offSet) {
MyS7Entity myData = this.s7Serializer.dispense(clazz.getClass(), dbNum, offSet);
return myData;
}
@Override
public void writePlcData(Integer dbNum, MyS7WriteEntity clazz){
this.s7Serializer.store(clazz,dbNum,0);
}
//DB,DB号,偏移量,Byte数组
@Override
public void writePlcByte(byte[] bytes){
this.s7Connector.write(DaveArea.DB,31,0,bytes);
}
}
package com.zg.myssm.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zg.myssm.entities.MyConfig;
import org.springframework.stereotype.Service;
import java.io.*;
/**
* @Auther: Zg
* @Date: 2022/9/9 - 09 - 09 - 9:26
* @Description: com.zg.sboottest.commhelper
* @version: 1.0
*/
//@Builder
//@Data
//@AllArgsConstructor
//@NoArgsConstructor
//@Slf4j
@Service
public class MyJsonConfigTool {
public String jsonStr="D:\\modbuscfg.json";
public void CreatJson( MyConfig config) throws IOException {
// 创建文件对象
File fileText = new File(jsonStr);
ObjectMapper mapper = new ObjectMapper();
// 向文件写入对象写入信息
FileWriter fileWriter = new FileWriter(fileText);
// 写文件
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(config);
fileWriter.write(jsonString);
// 关闭
fileWriter.close();
}
public MyConfig ReadJson() throws IOException {
ObjectMapper mapper = new ObjectMapper();
File file = new File(jsonStr);
String str = getStr(file);
MyConfig myConfig = mapper.readValue(str, MyConfig.class);
return myConfig;
}
public String getStr(File jsonFile){
String jsonStr = "";
try {
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
/*
public class DataOutAndInStreamDemo {
public static void main(String[] args) throws IOException {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\java.txt"));
dos.writeUTF("α");
dos.writeInt(1234567);
dos.writeBoolean(true);
dos.writeShort((short)123);
dos.writeLong((long)456);
dos.writeDouble(99.98);
DataInputStream dis = new DataInputStream(new FileInputStream("D:\\java.txt"));
System.out.println(dis.readUTF());
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readShort());
System.out.println(dis.readLong());
System.out.println(dis.readDouble());
dis.close();
dos.close();
}
}
* */
/**
示例//Java程序演示示例
//方法
//DataInputStream-
import java.io.*;
public class ReadIntOfDIS {
public static void main(String[] args) throws IOException {
InputStream is_stm = null;
DataInputStream dis_stm = null;
FileOutputStream fos_stm = null;
DataOutputStream dos_stm = null;
int[] i_arr = {
100,
200,
300,
400,
500
};
try {
//实例化FileInputStream-
//DataInputStream-, FileOutputStream
//和DataOutputStream-
fos_stm = new FileOutputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
dos_stm = new DataOutputStream(fos_stm);
//循环写入每个int直到结束
for (int val: i_arr) {
//通过使用writeInt()方法isto-
//写一个整数到
//DataOutputStream dos_stm-
dos_stm.writeInt(val);
}
is_stm = new FileInputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
dis_stm = new DataInputStream(is_stm);
//循环读取可用数据直到结束
while (dis_stm.available() > 0) {
//通过使用readInt()isto方法读取
//整数
int in = dis_stm.readInt();
System.out.println("dis_stm.readInt(): " + in );
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
//要释放链接的系统资源
//这些流
if (is_stm != null)
is_stm.close();
if (dis_stm != null)
dis_stm.close();
if (dos_stm != null)
dos_stm.close();
if (fos_stm != null)
fos_stm.close();
}
}
}
输出结果dis_stm.readInt(): 100
dis_stm.readInt(): 200
dis_stm.readInt(): 300
dis_stm.readInt(): 400
dis_stm.readInt(): 500
*/
接口:
package com.zg.myssm.utils;
import com.zg.myssm.entities.MyDbData;
import com.zg.myssm.entities.MyGunData;
import java.io.IOException;
/**
* @Auther: Zg
* @Date: 2022/11/17 - 11 - 17 - 14:37
* @Description: com.zg.myssm.utils
* @version: 1.0
*/
public interface IS7ConnHelper {
void initConnect() throws IOException;
Object readPlcData(Integer dbNum, Class<?> clazz, int offSet);
MyGunData readTheDbData(Integer dbNum, MyGunData clazz, int offSet);
void writePlcData(Integer dbNum, MyGunData clazz, int offSet);
}
配置定时器多线程:
package com.zg.mymes.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
/**
* @Auther: Zg
* @Date: 2022/11/23 - 11 - 23 - 14:55
* @Description: com.zg.mymes.config
* @version: 1.0
*/
@Configuration
@EnableAsync
public class ScheduleConfig implements SchedulingConfigurer,AsyncConfigurer {
//spring.task.execution
@Bean("myTask")
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
//ThreadPoolTaskExecutor
taskScheduler.setPoolSize(20);
taskScheduler.setThreadNamePrefix("myTask-"); //设置线程名开头
//taskScheduler.setAwaitTerminationSeconds(60);
//taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
return taskScheduler;
}
////并行任务
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
TaskScheduler taskScheduler = taskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
}
//异步任务 异常处理
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return new SimpleAsyncUncaughtExceptionHandler();
}
}
变量实体类:
package com.zg.mymes.myConnPLC.myS7.myS7entities;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.annotation.DateTimeFormat;
import org.yaml.snakeyaml.scanner.Constant;
import java.util.Date;
/**
* @Auther: Zg
* @Date: 2022/11/23 - 11 - 23 - 17:13
* @Description: com.zg.mymes.myConnPLC.myS7.myS7entities
* @version: 1.0
* 可定制化的PLC值
*/
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
//@PropertySource("classpath:myS7Db.properties")
public class MyS7Entity {
// @TableId(type = IdType.AUTO)
// private Integer id;
//
// public static final Integer dbNum = 30;
// //@Value("${myS7Db.offSet}")
// public static final Integer offSet = 42;
//
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
// private Date createTime;
// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
// @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
// private Date insertTime;
//必须为public 否则报错
@S7Variable(byteOffset = 0, type = S7Type.REAL)
public Double aBLineVoltage_PLC;
@S7Variable(byteOffset = 4, type = S7Type.REAL)
public Double bCLineVoltage_PLC;
@S7Variable(byteOffset = 8, type = S7Type.REAL)
public Double aCLineVoltage_PLC;
@S7Variable(byteOffset = 12, type = S7Type.REAL)
public Double aPhaseVoltage_PLC;
@S7Variable(byteOffset = 16, type = S7Type.REAL)
public Double bPhaseVoltage_PLC;
@S7Variable(byteOffset = 20, type = S7Type.REAL)
public Double cPhaseVoltage_PLC;
@S7Variable(byteOffset = 24, type = S7Type.REAL)
public Double aPhaseCurrent_PLC;
@S7Variable(byteOffset = 28, type = S7Type.REAL)
public Double bPhaseCurrent_PLC;
@S7Variable(byteOffset = 32, type = S7Type.REAL)
public Double cPhaseCurrent_PLC;
@S7Variable(byteOffset = 36, type = S7Type.REAL)
public Double allActivePower_PLC;
@S7Variable(byteOffset = 40, type = S7Type.REAL)
public Double aActivePower_PLC;
@S7Variable(byteOffset = 44, type = S7Type.REAL)
public Double bActivePower_PLC;
@S7Variable(byteOffset = 48, type = S7Type.REAL)
public Double cActivePower_PLC;
@S7Variable(byteOffset = 52, type = S7Type.REAL)
public Double allReactivePower_PLC;
@S7Variable(byteOffset = 56, type = S7Type.REAL)
public Double aReactivePower_PLC;
@S7Variable(byteOffset = 60, type = S7Type.REAL)
public Double bReactivePower_PLC;
@S7Variable(byteOffset = 64, type = S7Type.REAL)
public Double cReactivePower_PLC;
@S7Variable(byteOffset = 68, type = S7Type.REAL)
public Double allPowerFactor_PLC;
@S7Variable(byteOffset = 72, type = S7Type.REAL)
public Double aPowerFactor_PLC;
@S7Variable(byteOffset = 76, type = S7Type.REAL)
public Double bPowerFactor_PLC;
@S7Variable(byteOffset = 80, type = S7Type.REAL)
public Double cPowerFactor_PLC;
@S7Variable(byteOffset = 84, type = S7Type.REAL)
public Double aBLineVoltage_Power;
@S7Variable(byteOffset = 88, type = S7Type.REAL)
public Double bCLineVoltage_Power;
@S7Variable(byteOffset = 92, type = S7Type.REAL)
public Double aCLineVoltage_Power;
@S7Variable(byteOffset = 96, type = S7Type.REAL)
public Double aPhaseVoltage_Power;
@S7Variable(byteOffset = 100, type = S7Type.REAL)
public Double bPhaseVoltage_Power;
@S7Variable(byteOffset = 104, type = S7Type.REAL)
public Double cPhaseVoltage_Power;
@S7Variable(byteOffset = 108, type = S7Type.REAL)
public Double aPhaseCurrent_Power;
@S7Variable(byteOffset = 112, type = S7Type.REAL)
public Double bPhaseCurrent_Power;
@S7Variable(byteOffset = 116, type = S7Type.REAL)
public Double cPhaseCurrent_Power;
@S7Variable(byteOffset = 120, type = S7Type.REAL)
public Double allActivePower_Power;
@S7Variable(byteOffset = 124, type = S7Type.REAL)
public Double aActivePower_Power;
@S7Variable(byteOffset = 128, type = S7Type.REAL)
public Double bActivePower_Power;
@S7Variable(byteOffset = 132, type = S7Type.REAL)
public Double cActivePower_Power;
@S7Variable(byteOffset = 136, type = S7Type.REAL)
public Double allReactivePower_Power;
@S7Variable(byteOffset = 140, type = S7Type.REAL)
public Double aReactivePower_Power;
@S7Variable(byteOffset = 144, type = S7Type.REAL)
public Double bReactivePower_Power;
@S7Variable(byteOffset = 148, type = S7Type.REAL)
public Double cReactivePower_Power;
@S7Variable(byteOffset = 152, type = S7Type.REAL)
public Double allPowerFactor_Power;
@S7Variable(byteOffset = 156, type = S7Type.REAL)
public Double aPowerFactor_Power;
@S7Variable(byteOffset = 160, type = S7Type.REAL)
public Double bPowerFactor_Power;
@S7Variable(byteOffset = 164, type = S7Type.REAL)
public Double cPowerFactor_Power;
@S7Variable(byteOffset = 168, type = S7Type.REAL)
public Double testAlarm;
@S7Variable(byteOffset = 404, type = S7Type.WORD)
public Integer heartBeat;
@S7Variable(byteOffset = 606,size = 130, type = S7Type.STRING)
public String var100;
@S7Variable(byteOffset = 738,size = 130, type = S7Type.STRING)
public String var101;
/**
@S7Variable(byteOffset=0, type= S7Type.REAL) public double var1;
@S7Variable(byteOffset=4, type= S7Type.REAL) public double var2;
@S7Variable(byteOffset=8, type= S7Type.REAL) public double var3;
@S7Variable(byteOffset=144, type= S7Type.BOOL) public boolean STATE_P1;
@S7Variable(byteOffset=144, type= S7Type.BOOL,bitOffset = 1) public boolean STATE_P1;
*/
}
package com.zg.myssm.entities;
import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Auther: Zg
* @Date: 2022/11/17 - 11 - 17 - 15:13
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyGunData {
@S7Variable(byteOffset = 0, type = S7Type.WORD)
public Integer var1;
@S7Variable(byteOffset = 2, type = S7Type.WORD)
public Integer var2;
@S7Variable(byteOffset = 4, type = S7Type.WORD)
public Integer var3;
@S7Variable(byteOffset = 6, type = S7Type.WORD)
public Integer var4;
@S7Variable(byteOffset = 8, type = S7Type.WORD)
public Integer var5;
@S7Variable(byteOffset = 10, type = S7Type.WORD)
public Integer var6;
@S7Variable(byteOffset = 12, type = S7Type.WORD)
public Integer var7;
@S7Variable(byteOffset = 14, type = S7Type.WORD)
public Integer var8;
@S7Variable(byteOffset = 16, type = S7Type.WORD)
public Integer var9;
@S7Variable(byteOffset = 18, type = S7Type.WORD)
public Integer var10;
// @S7Variable(type = S7Type.STRING, byteOffset = 2, bitOffset=0, size=10)
// public String bbb;
}
package com.zg.mymes.myConnPLC.myS7.myS7entities;
import com.github.s7connector.api.annotation.S7Variable;
import com.github.s7connector.impl.utils.S7Type;
/**
* @Auther: Zg
* @Date: 2022/11/30 - 11 - 30 - 10:58
* @Description: com.zg.mymes.myConnPLC.myS7.myS7entities
* @version: 1.0
*/
public class MyS7WriteEntity {
@S7Variable(byteOffset = 606,size = 130, type = S7Type.STRING)
public String var100;
@S7Variable(byteOffset = 738,size = 130, type = S7Type.STRING)
public String var101;
}
监听:
package com.zg.myssm.utils;
import com.github.s7connector.api.S7Connector;
import com.zg.myssm.entities.MyDbData;
import com.zg.myssm.entities.MyGunData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.IOException;
/**
* @Auther: Zg
* @Date: 2022/11/17 - 11 - 17 - 14:36
* @Description: com.zg.myssm.utils
* @version: 1.0
*/
@Service
@Slf4j
public class Listenner {
@Autowired
public S7ConnHelper s7ConnHelper;
Boolean last = false;
Boolean trigIn = false;
Boolean trigQ = false;
@PostConstruct
public void Conn() throws IOException {
s7ConnHelper.initConnect();
log.info("初始化成功!!");
}
//S7
@PostConstruct
public void Conn() throws IOException {
s7ConnHelper.initConnect();
log.info("初始化成功!!");
//MyS7Entity build = MyS7Entity.builder().var2(501).build();
//s7ConnHelper.writePlcData(build.dbNum,build,build.offSet);
}
//S7
@Async("myTask")
@Scheduled(cron = "*/1 * * * * *")
public void Listen(){
try {
s7ConnHelper.readPlcData(31, MyS7Entity.class, 0);
Map<String, Object> myMap = new HashMap<>();
Field[] fields = s7ConnHelper.getMyDbData().getClass().getFields();
for (Field f :fields
) {
//log.info(f.getType().toString());
if (f.get(s7ConnHelper.getMyDbData()) instanceof Double){
String format = String.format("%.3f", f.get(s7ConnHelper.getMyDbData()));
myMap.put(f.getName(),format);
}
else {
myMap.put(f.getName(),f.get(s7ConnHelper.getMyDbData()));
}
}
s7ConnHelper.setMyMap(myMap);
java.util.Date date = new Date();//获得当前时间
Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型,这样便可以存入到Mysql数据库中
for (ActualData actualData:s7ConnHelper.getActualDatas()
) {
actualData.setCreateTime(t);
actualData.setValue(myMap.get(actualData.getName()).toString());
//String s = Optional.ofNullable(actualData.getValue()).orElse("0");
if (StringUtils.isEmpty(actualData.getValue()))
{
actualData.setValue("0");
}
if (
actualData.getVarType().equals("Float")&&
actualData.getHighHighAlarm()!=null && actualData.getHighHighAlarm().length()!=0&&
actualData.getHighAlarm()!=null && actualData.getHighAlarm().length()!=0 &&
actualData.getLowLowAlarm()!=null && actualData.getLowLowAlarm().length()!=0 &&
actualData.getLowAlarm()!=null && actualData.getLowAlarm().length()!=0
){
if ((Double.parseDouble(actualData.getValue())>Double.parseDouble(actualData.getHighAlarm()))
&& (Double.parseDouble(actualData.getValue())<Double.parseDouble(actualData.getHighHighAlarm()))
){
actualData.setAlarmDescription("该变量高报警!");
actualData.setInsertTime(t);
actualDataService.save(actualData);
}
if (Double.parseDouble(actualData.getValue())>Double.parseDouble(actualData.getHighHighAlarm())){
actualData.setAlarmDescription("该变量高高报警!");
actualData.setInsertTime(t);
actualDataService.save(actualData);
}
if ((Double.parseDouble(actualData.getValue())<Double.parseDouble(actualData.getLowAlarm()))
&& (Double.parseDouble(actualData.getValue())>Double.parseDouble(actualData.getLowLowAlarm()))
){
actualData.setAlarmDescription("该变量低报警!");
actualData.setInsertTime(t);
actualDataService.save(actualData);
}
if (Double.parseDouble(actualData.getValue())<Double.parseDouble(actualData.getLowLowAlarm())){
actualData.setAlarmDescription("该变量低低报警!");
actualData.setInsertTime(t);
actualDataService.save(actualData);
}
}
}
s7ConnHelper.getActualDatas().forEach(actualData -> log.info(actualData.toString()));
log.info(Thread.currentThread().getName());
// for (String key: s7ConnHelper.getMyMap().keySet()
// ) {
// System.out.println(key);
// }
// System.out.println("===============");
// for (Object v: s7ConnHelper.getMyMap().values()
// ) {
// System.out.println(v);
// }
}
catch (Exception ex){
log.info(ex.getMessage()+"=====");
s7ConnHelper.s7Connector=null;
s7ConnHelper.s7Serializer=null;
try {
s7ConnHelper.initConnect();
errorTimes=0;
} catch (IOException e) {
e.printStackTrace();
}
}
////输出ActualData
// java.util.Date date = new Date();//获得当前时间
// Timestamp t = new Timestamp(date.getTime());//将时间转换成Timestamp类型,这样便可以存入到Mysql数据库中
// for (int i = 0 ; i<s7ConnHelper.getActualDatas().size();i++ ){
// String myScale = s7ConnHelper.getActualDatas().get(i).getScale();
// Double scale = Double.parseDouble(myScale);
// Double value =scale * s7ConnHelper.getMyDbDataList().get(i);
// s7ConnHelper.getActualDatas().get(i).setValue(String.format("%.2f",value));
// s7ConnHelper.getActualDatas().get(i).setCreateTime(t);
// }
//
// for (ActualData actualData: s7ConnHelper.getActualDatas()
// ) {
// log.info(actualData.toString());
// }
//写入变量,OK
// MyGunData myGunData = new MyGunData();
// myDbData.setVar1(1);
// myDbData.setVar2(2);
// myDbData.setVar3(3);
// s7ConnHelper.writePlcData(24,myDbData,0);
}
}
启动类配置:
package com.zg.myssm;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
@MapperScan("com.zg.myssm.mapper")
//public class MyssmApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(MyssmApplication.class, args);
// }
//
//}
public class MyssmApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder){
return builder.sources(MyssmApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(MyssmApplication.class, args);
}
}
json文件:
{
"ip" : "192.168.2.11",
"port" : "502",
"slaveNo" : "1",
"address" : "0",
"actualDatas" : [ {
"id" : 1,
"name" : "aBLineVoltage_PLC",
"description" : "PLC柜_AB相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "0",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 2,
"name" : "bCLineVoltage_PLC",
"description" : "PLC柜_BC相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "1",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 3,
"name" : "aCLineVoltage_PLC",
"description" : "PLC柜_AC相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "2",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 4,
"name" : "aPhaseVoltage_PLC",
"description" : "PLC柜_A相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "3",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 5,
"name" : "bPhaseVoltage_PLC",
"description" : "PLC柜_B相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "4",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 6,
"name" : "cPhaseVoltage_PLC",
"description" : "PLC柜_C相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "5",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 7,
"name" : "aPhaseCurrent_PLC",
"description" : "PLC柜_A相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "6",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 8,
"name" : "bPhaseCurrent_PLC",
"description" : "PLC柜_B相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "7",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 9,
"name" : "cPhaseCurrent_PLC",
"description" : "PLC柜_C相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "8",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 10,
"name" : "allActivePower_PLC",
"description" : "PLC柜_合相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "9",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 11,
"name" : "aActivePower_PLC",
"description" : "PLC柜_A相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "10",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 12,
"name" : "bActivePower_PLC",
"description" : "PLC柜_B相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "11",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 13,
"name" : "cActivePower_PLC",
"description" : "PLC柜_C相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "12",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 14,
"name" : "allReactivePower_PLC",
"description" : "PLC柜_合相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "13",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 15,
"name" : "aReactivePower_PLC",
"description" : "PLC柜_A相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "14",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 16,
"name" : "bReactivePower_PLC",
"description" : "PLC柜_B相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "15",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 17,
"name" : "cReactivePower_PLC",
"description" : "PLC柜_C相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "16",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 18,
"name" : "allPowerFactor_PLC",
"description" : "PLC柜_合相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "17",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 19,
"name" : "aPowerFactor_PLC",
"description" : "PLC柜_A相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "18",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 20,
"name" : "bPowerFactor_PLC",
"description" : "PLC柜_B相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "19",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 21,
"name" : "cPowerFactor_PLC",
"description" : "PLC柜_C相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "20",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 22,
"name" : "aBLineVoltage_Power",
"description" : "电源柜_AB相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "21",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 23,
"name" : "bCLineVoltage_Power",
"description" : "电源柜_BC相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "22",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 24,
"name" : "aCLineVoltage_Power",
"description" : "电源柜_AC相线电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "23",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 25,
"name" : "aPhaseVoltage_Power",
"description" : "电源柜_A相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "24",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 26,
"name" : "bPhaseVoltage_Power",
"description" : "电源柜_B相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "25",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 27,
"name" : "cPhaseVoltage_Power",
"description" : "电源柜_C相相电压",
"createTime" : "",
"insertTime" : "",
"varAddress" : "26",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 28,
"name" : "aPhaseCurrent_Power",
"description" : "电源柜_A相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "27",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 29,
"name" : "bPhaseCurrent_Power",
"description" : "电源柜_B相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "28",
"varType" : "Float",
"scale" : "0.1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 30,
"name" : "cPhaseCurrent_Power",
"description" : "电源柜_C相相电流",
"createTime" : "",
"insertTime" : "",
"varAddress" : "29",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 31,
"name" : "allActivePower_Power",
"description" : "电源柜_合相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "30",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 32,
"name" : "aActivePower_Power",
"description" : "电源柜_A相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "31",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 33,
"name" : "bActivePower_Power",
"description" : "电源柜_B相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "32",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 34,
"name" : "cActivePower_Power",
"description" : "电源柜_C相有功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "33",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 35,
"name" : "allReactivePower_Power",
"description" : "电源柜_全相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "34",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 36,
"name" : "aReactivePower_Power",
"description" : "电源柜_A相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "35",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 37,
"name" : "bReactivePower_Power",
"description" : "电源柜_B相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "36",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 38,
"name" : "cReactivePower_Power",
"description" : "电源柜_C相无功功率",
"createTime" : "",
"insertTime" : "",
"varAddress" : "37",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 39,
"name" : "allPowerFactor_Power",
"description" : "电源柜_全相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "38",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 40,
"name" : "aPowerFactor_Power",
"description" : "电源柜_A相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "39",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 41,
"name" : "bPowerFactor_Power",
"description" : "电源柜_B相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "40",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 42,
"name" : "cPowerFactor_Power",
"description" : "电源柜_C相功率因数",
"createTime" : "",
"insertTime" : "",
"varAddress" : "41",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 43,
"name" : "testAlarm",
"description" : "报警测试",
"createTime" : "",
"insertTime" : "",
"varAddress" : "42",
"varType" : "Float",
"scale" : "1",
"highAlarm" : "300",
"highHighAlarm" : "400",
"lowAlarm" : "-100",
"lowLowAlarm" : "-200",
"alarmDescription" : "",
"value" : ""
},
{
"id" : 44,
"name" : "heartBeat",
"description" : "心跳",
"createTime" : "",
"insertTime" : "",
"varAddress" : "43",
"varType" : "Short",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 45,
"name" : "var100",
"description" : "字符串1",
"createTime" : "",
"insertTime" : "",
"varAddress" : "44",
"varType" : "String",
"scale" : "1",
"highAlarm" : "",
"highHighAlarm" : "",
"lowAlarm" : "",
"lowLowAlarm" : "",
"alarmDescription" : "",
"value" : ""
}, {
"id" : 46,
"name" : "var101",
"description" : "字符串2",
"createTime" : "",
"insertTime" : "",
"varAddress" : "45",
"varType" : "String",
"scale" : "1",
"highAlarm" : "100",
"highHighAlarm" : "200",
"lowAlarm" : "-10",
"lowLowAlarm" : "-100",
"alarmDescription" : "",
"value" : ""
}
]
}
ThreadPoolTaskExecutor用法和配置
package com.yomahub.tlog.example.feign.configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
*
*/
@Configuration
//@EnableAsync
@Slf4j
public class AsyncConfiguration implements AsyncConfigurer {
@Bean(name = "defaultPoolTaskExecutor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
taskExecutor.setCorePoolSize(2);
//线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
taskExecutor.setMaxPoolSize(10);
//缓存队列
taskExecutor.setQueueCapacity(50);
//许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
taskExecutor.setKeepAliveSeconds(200);
//异步方法内部线程名称
taskExecutor.setThreadNamePrefix("default-");
/**
* 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize,如果还有任务到来就会采取任务拒绝策略
* 通常有以下四种策略:
* ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
* ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
* ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
* ThreadPoolExecutor.CallerRunsPolicy:重试添加当前的任务,自动重复调用 execute() 方法,直到成功
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
/**
* 指定默认线程池
*/
@Override
public Executor getAsyncExecutor() {
return executor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) ->
log.error("线程池执行任务发送未知错误,执行方法:{}",method.getName(),ex);
}
}
package com.yomahub.tlog.example.feign.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
//@EnableAsync
public class SyncConfiguration {
@Bean(name = "otherTaskExecutor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心线程数
taskExecutor.setCorePoolSize(10);
//线程池维护线程的最大数量,只有在缓冲队列满了之后才会申请超过核心线程数的线程
taskExecutor.setMaxPoolSize(100);
//缓存队列
taskExecutor.setQueueCapacity(50);
//许的空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
taskExecutor.setKeepAliveSeconds(200);
//异步方法内部线程名称
taskExecutor.setThreadNamePrefix("other-");
/**
* 当线程池的任务缓存队列已满并且线程池中的线程数目达到maximumPoolSize,如果还有任务到来就会采取任务拒绝策略
* 通常有以下四种策略:
* ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。
* ThreadPoolExecutor.DiscardPolicy:也是丢弃任务,但是不抛出异常。
* ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程)
* ThreadPoolExecutor.CallerRunsPolicy:重试添加当前的任务,自动重复调用 execute() 方法,直到成功
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
package com.yomahub.tlog.example.feign.service;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AsyncTask {
@SneakyThrows
@Async("defaultPoolTaskExecutor")
// @Async
public void doTask1() {
long t1 = System.currentTimeMillis();
Thread.sleep(2000);
long t2 = System.currentTimeMillis();
log.info("task1 cost {} ms,thread name {}" , (t2-t1),Thread.currentThread().getName());
}
@SneakyThrows
@Async("otherTaskExecutor")
// @Async
public void doTask2() {
long t1 = System.currentTimeMillis();
Thread.sleep(3000);
long t2 = System.currentTimeMillis();
log.info("task2 cost {} ms,thread name {}" , (t2-t1),Thread.currentThread().getName());
}
}
package com.yomahub.tlog.example.feign.controller;
import com.yomahub.tlog.example.feign.service.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//SpringBoot 如何实现异步编程?大神都是这么玩的!
@RestController
@RequestMapping("/async")
@Slf4j
public class AsyncController {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/task")
public void task() throws InterruptedException {
long t1 = System.currentTimeMillis();
asyncTask.doTask1();
asyncTask.doTask2();
Thread.sleep(1000);
long t2 = System.currentTimeMillis();
log.info("main cost {} ms", t2 - t1);
}
}
spring.application.name=tlog-logback-feign-consumer
server.port=3111
#eureka.client.service-url.defaultZone=http://127.0.0.1:1111/eureka/
tlog.pattern=[$currIp][$spanId][$traceId]
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
http.connectTimeOutMillis=8000
http.readTimeOutMillis=8000
spring.task.execution.pool.core-size=5
spring.task.execution.pool.max-size=50
spring.task.execution.pool.queue-capacity=200
spring.task.execution.thread-name-prefix=woniugege-