Przeglądaj źródła

后台连接netty

985653680@qq.com 1 rok temu
rodzic
commit
bdb838680f

+ 71 - 0
src/main/java/com/gzlh/background/client/BackgroundClientHandler.java

@@ -0,0 +1,71 @@
+package com.gzlh.background.client;
+
+import com.gzlh.socket.CustomHeartbeatHandler;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+@ChannelHandler.Sharable
+public class BackgroundClientHandler extends CustomHeartbeatHandler {
+    private BackgroundClientNetty client;
+
+    public BackgroundClientHandler(BackgroundClientNetty client) {
+        super("client");
+        this.client = client;
+    }
+
+
+//    @Override
+//    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
+//        System.out.println(1111);
+//        System.out.println("Client received: " + msg);
+//
+//    }
+
+
+    //    @Override
+//    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
+//        System.out.println(1111);
+//        System.out.println(msg);
+////        ByteBuf in = (ByteBuf) msg;
+////        System.out.println("Client received: " + in.toString(CharsetUtil.UTF_8));
+//
+//    }
+
+    @Override
+    protected void handleData(ChannelHandlerContext channelHandlerContext, String msg) {
+//        byte[] data = new byte[byteBuf.readableBytes() - 5];
+//        byteBuf.skipBytes(5);
+//        byteBuf.readBytes(data);
+//        String content = new String(data);
+        System.out.println(name + " get content: " + msg);
+    }
+
+    @Override
+    protected void handleAllIdle(ChannelHandlerContext ctx) {
+        super.handleAllIdle(ctx);
+        sendPingMsg(ctx);
+    }
+
+
+//    @Override
+//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+//        //当被通知Channel是活跃的时候,发送一条消息
+////        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
+////        sendPingMsg(ctx);
+//    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
+        cause.printStackTrace();
+        ctx.close();
+    }
+
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        super.channelInactive(ctx);
+        client.connect();
+    }
+
+}

+ 91 - 0
src/main/java/com/gzlh/background/client/BackgroundClientNetty.java

@@ -0,0 +1,91 @@
+package com.gzlh.background.client;
+
+import com.gzlh.background.properties.BackgroundPropertiesConfig;
+import com.gzlh.led.properties.LedPropertiesConfig;
+import com.gzlh.socket.TestClientHandler;
+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.codec.string.StringDecoder;
+import io.netty.handler.codec.string.StringEncoder;
+import io.netty.handler.timeout.IdleStateHandler;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.annotation.Resource;
+import java.util.concurrent.TimeUnit;
+
+@Configuration
+@Slf4j
+public class BackgroundClientNetty {
+
+    @Resource
+    private BackgroundPropertiesConfig config;
+    @Autowired
+    private BackgroundClientHandler backgroundClientHandler;
+    Bootstrap bootstrap;
+    Channel channel;
+
+
+    @Bean("backgroundClient")
+    public Bootstrap bootstrap() {
+        EventLoopGroup group = new NioEventLoopGroup();
+        bootstrap = new Bootstrap();
+        return bootstrap.group(group)
+                .channel(NioSocketChannel.class)
+                .remoteAddress(config.getHost(), config.getPort())
+                .handler(new ChannelInitializer<SocketChannel>() {
+                    @Override
+                    protected void initChannel(SocketChannel socketChannel) {
+                        socketChannel.pipeline()
+                                .addLast("decoder", new StringDecoder())
+                                .addLast("encoder", new StringEncoder())
+                                .addLast(new IdleStateHandler(0, 0, 5))
+                                .addLast(backgroundClientHandler);
+                    }
+                });
+
+    }
+
+    @Bean("backgroundClientHandler")
+    public BackgroundClientHandler backgroundClientHandler() {
+        return new BackgroundClientHandler(this);
+    }
+
+    public void connect() {
+        ChannelFuture future = bootstrap().connect();
+        future.addListener((ChannelFutureListener) future1 -> {
+            if (future1.isSuccess()) {
+                channel = future1.channel();
+                log.info("后端服务器连接成功,{},{}",config.getHost(), config.getPort());
+            } else {
+                log.error("------------后端-连接服务器失败,{},{}-----------,进行重连",config.getHost(), config.getPort());
+                future1.channel().eventLoop().schedule(this::connect, 5, TimeUnit.SECONDS);
+            }
+        });
+        try {
+            future.channel().closeFuture().sync();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
+
+    public void send(String message) {
+        if (channel != null && channel.isActive()) {
+            channel.writeAndFlush(message);
+        } else {
+            log.error("未建立连接,无法发送消息");
+        }
+    }
+
+    public void close() {
+        if (channel != null) {
+            channel.close();
+        }
+    }
+
+}

+ 91 - 0
src/main/java/com/gzlh/background/client/CustomHeartbeatHandler.java

@@ -0,0 +1,91 @@
+package com.gzlh.background.client;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.timeout.IdleStateEvent;
+
+public abstract class CustomHeartbeatHandler extends SimpleChannelInboundHandler<String> {
+    public static final byte PING_MSG = 1;
+    public static final byte PONG_MSG = 2;
+    public static final byte CUSTOM_MSG = 3;
+    protected String name;
+    private int heartbeatCount = 0;
+
+    public CustomHeartbeatHandler(String name) {
+        this.name = name;
+    }
+
+    @Override
+    protected void channelRead0(ChannelHandlerContext context, String msg) throws Exception {
+//        if (byteBuf.getByte(4) == PING_MSG) {
+//            sendPongMsg(context);
+//        } else if (byteBuf.getByte(4) == PONG_MSG){
+//            System.out.println(name + " get pong msg from " + context.channel().remoteAddress());
+//        } else {
+            handleData(context, msg);
+//        }
+    }
+
+    protected void sendPingMsg(ChannelHandlerContext context) {
+//        ByteBuf buf = context.alloc().buffer(5);
+//        buf.writeInt(5);
+//        buf.writeByte(PING_MSG);
+        context.writeAndFlush("ping");
+        heartbeatCount++;
+        System.out.println(name + " sent ping msg to " + context.channel().remoteAddress() + ", count: " + heartbeatCount);
+    }
+
+    protected void sendPongMsg(ChannelHandlerContext context) {
+//        ByteBuf buf = context.alloc().buffer(5);
+//        buf.writeInt(5);
+//        buf.writeByte(PONG_MSG);
+        context.channel().writeAndFlush("pong");
+        heartbeatCount++;
+        System.out.println(name + " sent pong msg to " + context.channel().remoteAddress() + ", count: " + heartbeatCount);
+    }
+
+    protected abstract void handleData(ChannelHandlerContext channelHandlerContext, String msg);
+
+    @Override
+    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
+        // IdleStateHandler 所产生的 IdleStateEvent 的处理逻辑.
+        if (evt instanceof IdleStateEvent) {
+            IdleStateEvent e = (IdleStateEvent) evt;
+            switch (e.state()) {
+                case READER_IDLE:
+                    handleReaderIdle(ctx);
+                    break;
+                case WRITER_IDLE:
+                    handleWriterIdle(ctx);
+                    break;
+                case ALL_IDLE:
+                    handleAllIdle(ctx);
+                    break;
+                default:
+                    break;
+            }
+        }
+    }
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) throws Exception {
+        System.err.println("---" + ctx.channel().remoteAddress() + " is active---");
+    }
+
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
+        System.err.println("---" + ctx.channel().remoteAddress() + " is inactive---");
+    }
+
+    protected void handleReaderIdle(ChannelHandlerContext ctx) {
+        System.err.println("---READER_IDLE---");
+    }
+
+    protected void handleWriterIdle(ChannelHandlerContext ctx) {
+        System.err.println("---WRITER_IDLE---");
+    }
+
+    protected void handleAllIdle(ChannelHandlerContext ctx) {
+        System.err.println("---ALL_IDLE---");
+    }
+}

+ 0 - 81
src/main/java/com/gzlh/config/RedisConfig.java

@@ -1,81 +0,0 @@
-package com.gzlh.config;
-
-import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import org.springframework.cache.CacheManager;
-import org.springframework.cache.annotation.CachingConfigurerSupport;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.redis.cache.RedisCacheConfiguration;
-import org.springframework.data.redis.cache.RedisCacheManager;
-import org.springframework.data.redis.cache.RedisCacheWriter;
-import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.*;
-
-import java.time.Duration;
-
-import static java.util.Collections.singletonMap;
-
-@Configuration
-@EnableCaching // 开启缓存支持
-public class RedisConfig extends CachingConfigurerSupport {
-	private static final String TEST_DEMO_CACHE = "test:demo";
-
-	/**
-	 * RedisTemplate配置
-	 *
-	 * @param lettuceConnectionFactory
-	 * @return
-	 */
-	@Bean
-	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
-		// 设置序列化
-		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
-		ObjectMapper om = new ObjectMapper();
-		om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
-		om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
-		om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
-		jackson2JsonRedisSerializer.setObjectMapper(om);
-		// 配置redisTemplate
-		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
-		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
-		RedisSerializer<?> stringSerializer = new StringRedisSerializer();
-		redisTemplate.setKeySerializer(stringSerializer);// key序列化
-		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
-		redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
-		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
-		redisTemplate.afterPropertiesSet();
-		return redisTemplate;
-	}
-
-	/**
-	 * 缓存配置管理器
-	 *
-	 * @param factory
-	 * @return
-	 */
-	@Bean
-	public CacheManager cacheManager(LettuceConnectionFactory factory) {
-        // 配置序列化(缓存默认有效期 6小时)
-        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(6));
-        RedisCacheConfiguration redisCacheConfiguration = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
-                												.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
-
-		// 以锁写入的方式创建RedisCacheWriter对象
-		//RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
-		// 创建默认缓存配置对象
-		/* 默认配置,设置缓存有效期 1小时*/
-		//RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));
-		/* 自定义配置test:demo 的超时时间为 5分钟*/
-		RedisCacheManager cacheManager = RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter(factory)).cacheDefaults(redisCacheConfiguration)
-				.withInitialCacheConfigurations(singletonMap(TEST_DEMO_CACHE, RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(5)).disableCachingNullValues()))
-				.transactionAware().build();
-		return cacheManager;
-	}
-
-}

+ 0 - 78
src/main/java/com/gzlh/controller/TestController.java

@@ -1,78 +0,0 @@
-package com.gzlh.controller;
-
-import cn.hutool.core.bean.BeanUtil;
-import cn.hutool.core.util.XmlUtil;
-import cn.hutool.extra.spring.SpringUtil;
-import com.gzlh.event.EventBus;
-import com.gzlh.utils.FileUtils;
-import com.gzlh.utils.RedisUtil;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.util.StringUtils;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import javax.annotation.Resource;
-import java.io.*;
-import java.net.Socket;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.*;
-
-
-@RestController
-@RequestMapping("/test")
-public class TestController {
-    @Value("${file.root-path}")
-    private String path;
-    @Value("${application.channel-name}")
-    private String channel;
-    @Autowired
-    private RedisUtil redisUtil;
-
-    @PostMapping("/t")
-    public void test(
-            @RequestBody String xmlStr
-//            HttpServletRequest request
-    ) throws IOException {
-//        String xmlStr = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
-
-        Map<String, Object> StringObjectMap = new HashMap<>();
-
-        XmlUtil.xmlToMap(xmlStr, StringObjectMap);
-
-        Map<String, Object> ic = BeanUtil.beanToMap(StringObjectMap.get("IC"));
-        Map<String, Object> weight =BeanUtil.beanToMap(StringObjectMap.get("WEIGHT"));
-        Map<String, Object> car = BeanUtil.beanToMap(StringObjectMap.get("CAR"));
-        Map<String, Object> conta =BeanUtil.beanToMap(StringObjectMap.get("CONTA"));
-        Map<String, Object> seal = BeanUtil.beanToMap(StringObjectMap.get("SEAL"));
-
-
-        Map<String, String> cacheMap = new HashMap<>();
-        cacheMap.put("carEcNo", (String) car.get("CAR_EC_NO"));
-        cacheMap.put("contaIdF", !StringUtils.isEmpty((String) car.get("CONTA_ID_F"))?(String) car.get("CONTA_ID_F"):"");
-        cacheMap.put("contaIdB", !StringUtils.isEmpty((String) car.get("CONTA_ID_B"))?(String) car.get("CONTA_ID_B"):"");
-        redisUtil.set(channel,cacheMap);
-//        System.out.println(redisUtil.hasKey(channel));
-
-        Calendar calendar = Calendar.getInstance();
-        String savePath=path+"/"+ calendar.get(Calendar.YEAR)+"-" + (calendar.get(Calendar.MONTH)+1);
-
-        Map<String, String> picMap = new HashMap<>();
-        for (Map.Entry<String, Object> entry : conta.entrySet()) {
-            if(entry.getKey().contains("PIC")&& !StringUtils.isEmpty((String) entry.getValue())){
-                String filePath = FileUtils.downLoad((String) entry.getValue(),savePath);
-                String base64 = FileUtils.getBase64FromImg(filePath);
-                picMap.put(entry.getKey(),base64);
-            }
-        }
-
-        EventBus eventBus = SpringUtil.getBean(EventBus.class);
-        eventBus.start("WEIGHBRIDGE.READ");
-
-    }
-
-
-}

+ 11 - 0
src/main/java/com/gzlh/startup/StartupCommandLineRunner.java

@@ -4,14 +4,18 @@ import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.thread.ThreadUtil;
 import cn.hutool.json.JSONObject;
 import cn.hutool.json.XML;
+import com.gzlh.background.client.BackgroundClientNetty;
+import com.gzlh.background.properties.BackgroundPropertiesConfig;
 import com.gzlh.dto.ApplicationConfigDTO;
 import com.gzlh.event.EventBus;
 import com.gzlh.led.client.LedNettyConfig;
 import com.gzlh.led.properties.LedPropertiesConfig;
 import com.gzlh.infrared.client.RedNettyConfig;
 import com.gzlh.infrared.config.RedPropertiesConfig;
+import com.gzlh.socket.TestClientNetty;
 import com.gzlh.weighbridge.client.WeighbridgeNettyConfig;
 import com.gzlh.weighbridge.config.WeighbridgePropertiesConfig;
+import javafx.scene.layout.Background;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.boot.CommandLineRunner;
 import org.springframework.stereotype.Component;
@@ -37,6 +41,10 @@ public class StartupCommandLineRunner implements CommandLineRunner {
     private RedNettyConfig redNettyConfig;
     @Resource
     private RedPropertiesConfig redConfig;
+    @Resource
+    private BackgroundPropertiesConfig backgroundPropertiesConfig;
+    @Resource
+    private BackgroundClientNetty backgroundClientNetty;
 
     @Override
     public void run(String... args) throws Exception {
@@ -50,6 +58,9 @@ public class StartupCommandLineRunner implements CommandLineRunner {
         if (redConfig.isEnable()) {
             ThreadUtil.execute(() -> redNettyConfig.connect());
         }
+        if (backgroundPropertiesConfig.isEnable()) {
+            ThreadUtil.execute(() -> backgroundClientNetty.connect());
+        }
     }
 
     private void initConfig() {

+ 0 - 575
src/main/java/com/gzlh/utils/RedisUtil.java

@@ -1,575 +0,0 @@
-package com.gzlh.utils;
-
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.stereotype.Component;
-import org.springframework.util.CollectionUtils;
-
-import javax.annotation.Resource;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-/**
- * redis 工具类
- * @Author Scott
- *
- */
-@Component
-@Slf4j
-public class RedisUtil {
-
-	@Resource
-	private RedisTemplate<String, Object> redisTemplate;
-
-	/**
-	 * 指定缓存失效时间
-	 *
-	 * @param key  键
-	 * @param time 时间(秒)
-	 * @return
-	 */
-	public boolean expire(String key, long time) {
-		try {
-			if (time > 0) {
-				redisTemplate.expire(key, time, TimeUnit.SECONDS);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 根据key 获取过期时间
-	 *
-	 * @param key 键 不能为null
-	 * @return 时间(秒) 返回0代表为永久有效
-	 */
-	public long getExpire(String key) {
-		return redisTemplate.getExpire(key, TimeUnit.SECONDS);
-	}
-
-	/**
-	 * 判断key是否存在
-	 *
-	 * @param key 键
-	 * @return true 存在 false不存在
-	 */
-	public boolean hasKey(String key) {
-		try {
-			return redisTemplate.hasKey(key);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 删除缓存
-	 *
-	 * @param key 可以传一个值 或多个
-	 */
-	@SuppressWarnings("unchecked")
-	public void del(String... key) {
-		if (key != null && key.length > 0) {
-			if (key.length == 1) {
-				redisTemplate.delete(key[0]);
-			} else {
-				redisTemplate.delete(CollectionUtils.arrayToList(key));
-			}
-		}
-	}
-
-	// ============================String=============================
-	/**
-	 * 普通缓存获取
-	 *
-	 * @param key 键
-	 * @return 值
-	 */
-	public Object get(String key) {
-		return key == null ? null : redisTemplate.opsForValue().get(key);
-	}
-
-	public String get(String key, long start, long end){
-		return key == null ? null : redisTemplate.opsForValue().get(key,start,end);
-	}
-
-	/**
-	 * 普通缓存放入
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @return true成功 false失败
-	 */
-	public boolean set(String key, Object value) {
-		try {
-			redisTemplate.opsForValue().set(key, value);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-
-	}
-
-	/**
-	 * 普通缓存放入并设置时间
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
-	 * @return true成功 false 失败
-	 */
-	public boolean set(String key, Object value, long time) {
-		try {
-			if (time > 0) {
-				redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
-			} else {
-				set(key, value);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 递增
-	 *
-	 * @param key 键
-	 * @param delta  要增加几(大于0)
-	 * @return
-	 */
-	public long incr(String key, long delta) {
-		if (delta < 0) {
-			throw new RuntimeException("递增因子必须大于0");
-		}
-		return redisTemplate.opsForValue().increment(key, delta);
-	}
-
-	/**
-	 * 递减
-	 *
-	 * @param key 键
-	 * @param delta  要减少几(小于0)
-	 * @return
-	 */
-	public long decr(String key, long delta) {
-		if (delta < 0) {
-			throw new RuntimeException("递减因子必须大于0");
-		}
-		return redisTemplate.opsForValue().increment(key, -delta);
-	}
-
-	// ================================Map=================================
-	/**
-	 * HashGet
-	 *
-	 * @param key  键 不能为null
-	 * @param item 项 不能为null
-	 * @return 值
-	 */
-	public Object hget(String key, String item) {
-		return redisTemplate.opsForHash().get(key, item);
-	}
-
-	/**
-	 * 获取hashKey对应的所有键值
-	 *
-	 * @param key 键
-	 * @return 对应的多个键值
-	 */
-	public Map<Object, Object> hmget(String key) {
-		return redisTemplate.opsForHash().entries(key);
-	}
-
-	/**
-	 * HashSet
-	 *
-	 * @param key 键
-	 * @param map 对应多个键值
-	 * @return true 成功 false 失败
-	 */
-	public boolean hmset(String key, Map<String, Object> map) {
-		try {
-			redisTemplate.opsForHash().putAll(key, map);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * HashSet 并设置时间
-	 *
-	 * @param key  键
-	 * @param map  对应多个键值
-	 * @param time 时间(秒)
-	 * @return true成功 false失败
-	 */
-	public boolean hmset(String key, Map<String, Object> map, long time) {
-		try {
-			redisTemplate.opsForHash().putAll(key, map);
-			if (time > 0) {
-				expire(key, time);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 向一张hash表中放入数据,如果不存在将创建
-	 *
-	 * @param key   键
-	 * @param item  项
-	 * @param value 值
-	 * @return true 成功 false失败
-	 */
-	public boolean hset(String key, String item, Object value) {
-		try {
-			redisTemplate.opsForHash().put(key, item, value);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 向一张hash表中放入数据,如果不存在将创建
-	 *
-	 * @param key   键
-	 * @param item  项
-	 * @param value 值
-	 * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
-	 * @return true 成功 false失败
-	 */
-	public boolean hset(String key, String item, Object value, long time) {
-		try {
-			redisTemplate.opsForHash().put(key, item, value);
-			if (time > 0) {
-				expire(key, time);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 删除hash表中的值
-	 *
-	 * @param key  键 不能为null
-	 * @param item 项 可以使多个 不能为null
-	 */
-	public void hdel(String key, Object... item) {
-		redisTemplate.opsForHash().delete(key, item);
-	}
-
-	/**
-	 * 判断hash表中是否有该项的值
-	 *
-	 * @param key  键 不能为null
-	 * @param item 项 不能为null
-	 * @return true 存在 false不存在
-	 */
-	public boolean hHasKey(String key, String item) {
-		return redisTemplate.opsForHash().hasKey(key, item);
-	}
-
-	/**
-	 * hash递增 如果不存在,就会创建一个 并把新增后的值返回
-	 *
-	 * @param key  键
-	 * @param item 项
-	 * @param by   要增加几(大于0)
-	 * @return
-	 */
-	public double hincr(String key, String item, double by) {
-		return redisTemplate.opsForHash().increment(key, item, by);
-	}
-
-	/**
-	 * hash递减
-	 *
-	 * @param key  键
-	 * @param item 项
-	 * @param by   要减少记(小于0)
-	 * @return
-	 */
-	public double hdecr(String key, String item, double by) {
-		return redisTemplate.opsForHash().increment(key, item, -by);
-	}
-
-	// ============================set=============================
-	/**
-	 * 根据key获取Set中的所有值
-	 *
-	 * @param key 键
-	 * @return
-	 */
-	public Set<Object> sGet(String key) {
-		try {
-			return redisTemplate.opsForSet().members(key);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return null;
-		}
-	}
-
-	/**
-	 * 根据value从一个set中查询,是否存在
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @return true 存在 false不存在
-	 */
-	public boolean sHasKey(String key, Object value) {
-		try {
-			return redisTemplate.opsForSet().isMember(key, value);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 将数据放入set缓存
-	 *
-	 * @param key    键
-	 * @param values 值 可以是多个
-	 * @return 成功个数
-	 */
-	public long sSet(String key, Object... values) {
-		try {
-			return redisTemplate.opsForSet().add(key, values);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-
-	/**
-	 * 将set数据放入缓存
-	 *
-	 * @param key    键
-	 * @param time   时间(秒)
-	 * @param values 值 可以是多个
-	 * @return 成功个数
-	 */
-	public long sSetAndTime(String key, long time, Object... values) {
-		try {
-			Long count = redisTemplate.opsForSet().add(key, values);
-			if (time > 0) {
-				expire(key, time);
-			}
-			return count;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-
-	/**
-	 * 获取set缓存的长度
-	 *
-	 * @param key 键
-	 * @return
-	 */
-	public long sGetSetSize(String key) {
-		try {
-			return redisTemplate.opsForSet().size(key);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-
-	/**
-	 * 移除值为value的
-	 *
-	 * @param key    键
-	 * @param values 值 可以是多个
-	 * @return 移除的个数
-	 */
-	public long setRemove(String key, Object... values) {
-		try {
-			Long count = redisTemplate.opsForSet().remove(key, values);
-			return count;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-	// ===============================list=================================
-
-	/**
-	 * 获取list缓存的内容
-	 *
-	 * @param key   键
-	 * @param start 开始
-	 * @param end   结束 0 到 -1代表所有值
-	 * @return
-	 */
-	public List<Object> lGet(String key, long start, long end) {
-		try {
-			return redisTemplate.opsForList().range(key, start, end);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return null;
-		}
-	}
-
-	/**
-	 * 获取list缓存的长度
-	 *
-	 * @param key 键
-	 * @return
-	 */
-	public long lGetListSize(String key) {
-		try {
-			return redisTemplate.opsForList().size(key);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-
-	/**
-	 * 通过索引 获取list中的值
-	 *
-	 * @param key   键
-	 * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
-	 * @return
-	 */
-	public Object lGetIndex(String key, long index) {
-		try {
-			return redisTemplate.opsForList().index(key, index);
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return null;
-		}
-	}
-
-	/**
-	 * 将list放入缓存
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @return
-	 */
-	public boolean lSet(String key, Object value) {
-		try {
-			redisTemplate.opsForList().rightPush(key, value);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 将list放入缓存
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @param time  时间(秒)
-	 * @return
-	 */
-	public boolean lSet(String key, Object value, long time) {
-		try {
-			redisTemplate.opsForList().rightPush(key, value);
-			if (time > 0) {
-				expire(key, time);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 将list放入缓存
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @return
-	 */
-	public boolean lSet(String key, List<Object> value) {
-		try {
-			redisTemplate.opsForList().rightPushAll(key, value);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 将list放入缓存
-	 *
-	 * @param key   键
-	 * @param value 值
-	 * @param time  时间(秒)
-	 * @return
-	 */
-	public boolean lSet(String key, List<Object> value, long time) {
-		try {
-			redisTemplate.opsForList().rightPushAll(key, value);
-			if (time > 0) {
-				expire(key, time);
-			}
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 根据索引修改list中的某条数据
-	 *
-	 * @param key   键
-	 * @param index 索引
-	 * @param value 值
-	 * @return
-	 */
-	public boolean lUpdateIndex(String key, long index, Object value) {
-		try {
-			redisTemplate.opsForList().set(key, index, value);
-			return true;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return false;
-		}
-	}
-
-	/**
-	 * 移除N个值为value
-	 *
-	 * @param key   键
-	 * @param count 移除多少个
-	 * @param value 值
-	 * @return 移除的个数
-	 */
-	public long lRemove(String key, long count, Object value) {
-		try {
-			Long remove = redisTemplate.opsForList().remove(key, count, value);
-			return remove;
-		} catch (Exception e) {
-			log.error("系统异常",e);
-			return 0;
-		}
-	}
-}

+ 11 - 26
src/main/resources/application.yml

@@ -3,6 +3,7 @@ server:
 application:
   server-url: http://127.0.0.1:8099/pro
   channel-name: "A1园内地磅通道"
+  channel-code:
 
 weighbridge:
   host: 127.0.0.1
@@ -24,32 +25,16 @@ red:
 gate:
   brand: 4000
   gate-port: 8131
+camera:
+  host: 127.0.0.1
+  brand: 1000
+  port: 8888
+  enable: false
+background:
+  host: 127.0.0.1
+  port: 8080
+  enable: true
+
 file:
   root-path: D:\\upfile\\
 
-socket:
-  port: 8080
-
-Spring:
-  # redis 配置
-  redis:
-    # 地址
-    host: localhost
-    # 端口,默认为6379
-    port: 6379
-    # 数据库索引
-    database: 0
-    # 密码
-    password:
-    # 连接超时时间
-    timeout: 60s
-    lettuce:
-      pool:
-        # 连接池中的最小空闲连接
-        min-idle: 0
-        # 连接池中的最大空闲连接
-        max-idle: 8
-        # 连接池的最大数据库连接数
-        max-active: 8
-        # #连接池最大阻塞等待时间(使用负值表示没有限制)
-        max-wait: -1ms