socket接收到设备上报的数据,无法调用service层进行查询等操作
public class ServerSocketConfig {
private static Logger log = LoggerFactory.getLogger(ServerSocketConfig.class);
public static ServerSocket serverSocket = null;
/**
* corePoolSize :线程池中核心线程数的最大值
* maximumPoolSize :线程池中能拥有最多线程数
* keepAliveTime :表示空闲线程的存活时间
* TimeUnit unit :表示keepAliveTime的单位
* workQueue:用于缓存任务的阻塞队列
*/
private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
@Bean
public void socketCreate() {
try {
serverSocket = new ServerSocket(9000);
log.info("socket服务端开启");
while (true){
Socket socket = serverSocket.accept();
System.out.println("接收到客户端socket" + socket.getRemoteSocketAddress());
threadpool.execute(new ReceiveThread(socket, new StationServiceImpl()));
}
} catch (IOException e) {
log.info("socket服务启动异常");
e.printStackTrace();
}
}
}
class ReceiveThread implements Runnable {
private static Logger log = LoggerFactory.getLogger(ReceiveThread.class);
private Socket socket;
private IStationService stationService;
public ReceiveThread(Socket socket, IStationService stationService) {
this.socket = socket;
this.stationService = stationService;
}
@Override
public synchronized void run() {
try {
InputStream is = socket.getInputStream();
byte[] buf = new byte[1024];
int line = 0;
while((line=is.read(buf))!=-1){
//将接收到的数据在控制台输出
// byte[] 转换 (C语言中,byte类型没有符号位,最大值为255,java中byte类型带有符号位,最大值为127,问题就出现了)
int[] dataFormat=new int[500];
for(int i=0;i<line;i++){
if(buf[i]<0){
dataFormat[i]=buf[i]&0xff;
}else{
dataFormat[i]=buf[i];
}
System.out.print(dataFormat[i]+" ");
}
System.out.println("");
// 十进制转字符
String IMEI = "";
for (int i = 0; i < line; i++) {
if(i > 3 && i < 19) {
IMEI += (char)dataFormat[i];
}
}
System.out.println("IMEI : "+IMEI);
Station station = stationService.selectStationByIMEI(IMEI);
}
log.info("服务端关闭客户端[{}]", socket.getRemoteSocketAddress());
socket.close();
} catch (Exception e) {
log.info("接收数据异常socket关闭");
e.printStackTrace();
}
}
}
重点就在
Station station = stationService.selectStationByIMEI(IMEI);
运行时,在service层 stationMapper 为 null。
代码报错
我猜测可能是线程内不能直接调用外部方法,但不知道怎么解决。如果这样解决不了就要考虑通过HTTP将数据发送到其他接口去进行处理了。