netty高并发项目的boss/worker线程数,和业务线程数如何设置? 5C

用netty搭建的高并发项目,比如游戏服务端,boss/worker和业务线程数如何确定?

1个回答

netty是异步的,线程数可以不动,默认2倍核心数。
业务线程数可以参考这篇文章,io密集型2倍核心数,计算密集型1倍核心数,避免线程上下文切换带来的开销。
https://www.cnblogs.com/jpfss/p/11016169.html

yyjjttww
yyjjttww 回复SwordOfWarrior: 会的,所以需要设置一个合理的值啊。线程池大小= 核心数 /(等待时间/工作时间)。
10 个月之前 回复
SwordOfWarrior
SwordOfWarrior 线程数过多不是会增加线程切换的开销吗?
10 个月之前 回复
SwordOfWarrior
SwordOfWarrior 嗯嗯,一般是这样子的。但是这样应用内总的线程数至少是3倍核心数,这个数量是合理的吗?
10 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于netty工作线程并发的问题。

最近在做一个项目的压测是有关netty并发的。 1.工作线程coresize设置最小20,最大100,但是worker线程数一直都是20从来没超过,也增加过并发量,不知道是什么原因。 2.尝试把coresize调整为50,工作线程只创建到48。 想请教下, 1中为何线程数达不到最大线程设置; work线程的工作机制究竟是咋么样; 现打算进行调优,该从哪方面下手。

netty 高并发快速响应

现业务是接收http post请求并必须在15毫秒内返回, 我的实现思路: 1:首先netty接收完数据,验证contenttype等header信息再将post的数据protobuf反序列化成对象(必须), 2:然后将对象传入到某个方法, 3:该方法必须定时10毫秒完成,如果没有完成就直接返回null和请求的header 具体实现是: netty 主线程接收完数据转成request对象传到1号线程池里面,1号线程池验证对象和反序列化,传给2号线程池并wait10毫秒然后直接得到2号线程池的返回对象,有就有,没有就是null,然后再channel返回。2号线程池主要处理业务生成对象供1号线程池调用。 Linux version 2.6.32-431.11.25.el6.ucloud.x86_64 gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) Mem: 16G CPU(s): 8 sysctl.conf: net.ipv4.ip_forward = 0 net.ipv4.conf.default.rp_filter = 1 net.ipv4.conf.default.accept_source_route = 0 kernel.core_uses_pid = 1 net.ipv4.tcp_syncookies = 1 net.bridge.bridge-nf-call-ip6tables = 0 net.bridge.bridge-nf-call-iptables = 0 net.bridge.bridge-nf-call-arptables = 0 kernel.msgmnb = 65536 kernel.msgmax = 65536 kernel.shmmax = 68719476736 kernel.shmall = 4294967296 net.netfilter.nf_conntrack_max = 1000000 kernel.unknown_nmi_panic = 0 kernel.sysrq = 1 fs.file-max = 1000000 vm.swappiness = 10 fs.inotify.max_user_watches = 10000000 net.core.wmem_max = 67108864 net.core.rmem_max = 67108864 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 net.ipv4.conf.all.secure_redirects = 0 net.ipv4.conf.default.secure_redirects = 0 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.default.accept_redirects = 0 fs.notify.max_queued_events = 3276792 net.ipv4.neigh.default.gc_thresh1 = 2048 net.ipv4.neigh.default.gc_thresh2 = 4096 net.ipv4.neigh.default.gc_thresh3 = 8192 net.ipv6.conf.all.disable_ipv6 = 1 ############## net.ipv4.tcp_max_tw_buckets = 6000 net.ipv4.ip_local_port_range = 1024 65000 net.ipv4.tcp_tw_recycle = 1 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_syncookies = 1 net.core.somaxconn = 262144 net.core.netdev_max_backlog = 262144 net.ipv4.tcp_max_orphans = 262144 net.ipv4.tcp_max_syn_backlog = 262144 net.ipv4.tcp_synack_retries = 1 net.ipv4.tcp_syn_retries = 1 net.ipv4.tcp_fin_timeout = 1 net.ipv4.tcp_keepalive_time = 30 #### net.ipv4.tcp_rmem = 4096 87380 67108864 net.ipv4.tcp_wmem = 4096 65536 67108864 net.core.netdev_max_backlog = 250000 net.ipv4.tcp_mtu_probing=1 net.ipv4.tcp_congestion_control=hybla jdk 1.8 现用tomcat同样配置执行是4000qps,超时率为4%; netty是1000qps,超时率为5%; netty: cpu使用10%左右 java -Xms10g -Xmx10g -XX:NewSize=7098m -XX:SurvivorRatio=16 -XX:+DisableExplicitGC -XX:+CMSScavengeBeforeRemark -XX:+UseConcMarkSweepGC -XX:+UParNewGC S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT 403776.0 403776.0 25637.9 0.0 6460800.0 5273672.7 3217408.0 0.0 27928.0 25782.3 3352.0 2883.6 2 0.042 2 1.411 1.453 netstat -apn | grep TIME_WAIT | wl -h 5733 现需要qps达到1w以上。希望收到你的回答或demo。谢谢 ps: akka ,但觉得个人写future和他差不多吧。

netty测试高并发的问题

先上代码,大家帮忙看下。 服务端: package Server; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; public class HelloServer { private static final int port = 7878; public void start() throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workGroup); b.channel(NioServerSocketChannel.class); b.option(ChannelOption.SO_BACKLOG, 1024); b.childHandler(new SCCHandler()); // 绑定端口 ChannelFuture f = b.bind(port).sync(); // 等待服务端监听端口关闭 f.channel().closeFuture().sync(); } finally { // 优雅的退出 bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } } public static void main(String[] args) { try { new HelloServer().start(); } catch (InterruptedException e) { e.printStackTrace(); } } } 客户端测试高并发的DEMO: package Client; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class HelloClient { public static void main(String[] args) throws Exception { ScheduledExecutorService scheduledThreadPool = Executors .newScheduledThreadPool(3000); for (int i = 0; i < 3000; i++) { scheduledThreadPool.schedule(new Runnable() { public void run() { try { System.out.println("go"); new HelloClient("192.168.2.88", 7878).start(); } catch (Exception e) { System.out.println("压力测试失败->" + e.toString()); } } }, 200, TimeUnit.MILLISECONDS); } System.out.println("压力测试提交完成"); } private final String host; private final int port; public HelloClient(String host, int port) { this.host = host; this.port = port; } public void start() throws Exception { System.out.println("链接服务器开始"); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class); // b.remoteAddress(new InetSocketAddress(host, port)); b.option(ChannelOption.TCP_NODELAY, true); b.handler(new ClientCCHandler()); // ChannelFuture f = b.connect().sync(); ChannelFuture f = b.connect(host, port); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } 到5000以上就就会出现无法连接的状态了……求解!!

dubbox 停止服务报错 jar已经引入

* Exception in thread "NettyServerWorker-thread-1" java.lang.NoClassDefFoundError: org/jboss/netty/util/internal/ByteBufferUtil at org.jboss.netty.channel.socket.nio.SocketSendBufferPool.releaseExternalResources(SocketSendBufferPool.java:380) at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:91) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) Exception in thread "NettyServerWorker-thread-4" at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) Exception in thread "NettyServerWorker-thread-3" Caused by: java.lang.ClassNotFoundException: org.jboss.netty.util.internal.ByteBufferUtil at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526) ... 8 more java.lang.NoClassDefFoundError: org/jboss/netty/util/internal/ByteBufferUtil at org.jboss.netty.channel.socket.nio.SocketSendBufferPool.releaseExternalResources(SocketSendBufferPool.java:380) at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:91) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) Exception in thread "NettyServerWorker-thread-5" java.lang.NoClassDefFoundError: org/jboss/netty/util/internal/ByteBufferUtil at org.jboss.netty.channel.socket.nio.SocketSendBufferPool.releaseExternalResources(SocketSendBufferPool.java:380) at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:91) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) Exception in thread "NettyServerWorker-thread-2" at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) java.lang.NoClassDefFoundError: org/jboss/netty/util/internal/ByteBufferUtil at org.jboss.netty.channel.socket.nio.SocketSendBufferPool.releaseExternalResources(SocketSendBufferPool.java:380) at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:91) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) java.lang.NoClassDefFoundError: org/jboss/netty/util/internal/ByteBufferUtil at org.jboss.netty.channel.socket.nio.SocketSendBufferPool.releaseExternalResources(SocketSendBufferPool.java:380) at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:91) at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)Disconnected from server

项目编译运行后报这个错,(在eclipse中不报)是什么原因。

java.lang.IllegalStateException at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1777) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:589) at io.netty.util.concurrent.DefaultPromise.setSuccess(DefaultPromise.java:397) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:150) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745) Exception in thread "nioEventLoopGroup-2-1" java.lang.NoClassDefFoundError: io/netty/util/concurrent/DefaultPromise$2 at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:589) at io.netty.util.concurrent.DefaultPromise.setSuccess(DefaultPromise.java:397) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:150) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.ClassNotFoundException: io.netty.util.concurrent.DefaultPromise$2 at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1892) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1735) ... 5 more Exception in thread "nioEventLoopGroup-3-1" java.lang.NoClassDefFoundError: io/netty/util/concurrent/DefaultPromise$2 at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:589) at io.netty.util.concurrent.DefaultPromise.setSuccess(DefaultPromise.java:397) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:150) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745) Exception in thread "nioEventLoopGroup-2-2" java.lang.NoClassDefFoundError: io/netty/util/concurrent/DefaultPromise$2 at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:589) at io.netty.util.concurrent.DefaultPromise.setSuccess(DefaultPromise.java:397) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:150) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745) Exception in thread "nioEventLoopGroup-3-2" java.lang.NoClassDefFoundError: io/netty/util/concurrent/DefaultPromise$2 at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:589) at io.netty.util.concurrent.DefaultPromise.setSuccess(DefaultPromise.java:397) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:150) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:745)

Netty多线程客户端服务器端通信

现在实现了Netty客户端服务器端编码解析json格式数据,如何是用多线程进行客户端服务器端的通信?进行tps统计? 有没有有经验的大佬点拨一下?

netty的channelRead方法是单线程调用还是多线程调用

输出的线程名显示是多线程调用,但是打断点之后所有的请求都阻塞了,是单线程还是多线程呢?在这个地方需要考虑并发问题吗?

netty短链接高并发的问题

场景:netty服务端在高并发的情况下,由于业务逻辑的修改,需要重启netty服务端的服务,重启后,出现了一种SYN-Flood攻击的现象,Tomcat服务崩溃,远程访问不服务器的情况。 想请问一下是什么原因造成的,有什么好的解决方法吗?一开始,netty服务端未处于高并发的情况时,重启是没问题的,但是高并发以后,就不能修改业务逻辑了吗?

netty,channel与线程过载

netty,一个连接一定是对应一个channel,那么一个连接多次发数据,是不是一定都对应这个channel呢? 一个channel是和一个线程绑定,那么一个连接数据量超大,会不会导致线程过载呢?

使用netty5,收消息和发消息是同一个线程吗

现在的问题是,我作为客户端通过netty连接一个服务端,接收到服务端的消息后,不开新线程,处理消息是串行的。这个没问题,但是我发消息也发不出去?这个不应该吧,难道netty的收消息和发消息使用的是同一个线程?

netty线程模型如何测试

netty权威指南中说netty的线程模型有以下特点 1.主从模式,主线程组负责处理链接accept,从线程组负责io处理和任务处理 2.串行模式,当一个io线程select到io就绪后就会直接在该线程调用pipline中的操作 另外当execute任务之前io线程也会selectnow一次,以执行就绪的io操作,从而实现串行化 请问有没有方法或思路对以上内容进行验证。就是我要测试上面内容的正确性需要如何编写代码 经过断点测试,发现server通道注册在主线程组的线程下,socket通道注册在从线程组的线程中,而且每个eventloop中注册的通道都不相同,execute是在线程组中的下一个eventloop中执行的,

java netty NoClassDefFoundError 找不到eventloop class

在eclipse上用用netty框架写了个demo,直接在eclipse上能编译运行成功,导出了个jar包, 用java -jar 运行后,报出了如下错误: Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError: io/netty/channel/Even tLoopGroup at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.privateGetMethodRecursive(Unknown Source) at java.lang.Class.getMethod0(Unknown Source) at java.lang.Class.getMethod(Unknown Source) at sun.launcher.LauncherHelper.validateMainClass(Unknown Source) at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) Caused by: java.lang.ClassNotFoundException: io.netty.channel.EventLoopGroup at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 7 more 最开始以为是包没打好, 又重新在manifest里面定义了一下classpath,完事一样还是找不到eventloopgroup class,我工程里面就引用了一个netty-5.0.0.Alpha2,我看了一下这个包,class文件好好的静静的就躺在那里........为什么它找不到,求大神们给个解决方案。。。。

netty多线程通信一次传输较大数据遇到的问题

您好,刚入门netty,想请教大神们几个问题,对于只有一个线程一次传输过大的数据,通过这个方法解决了:传输时头4个字节保存数据大小,后面保存内容,接收时如果发现读取的数据长度不够,则累积到下一次读取,最后得到的message则为需要的数据。部分代码如下: 发送消息: public static void sendMsg(ChannelHandlerContext ctx,byte[] bytes){ ByteBuf buf = ctx.alloc().buffer(); buf.writeInt(bytes.length); buf.writeBytes(bytes); ctx.writeAndFlush(buf); } 接收消息: public class Decoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { if (buf.readableBytes()<buf.getInt(buf.readerIndex())){ return; } out.add(buf.readBytes(buf.readableBytes())); } } 现在我有个情景是,在传输数据时是多线程的,同一个时间会多次调用ctx.writeAndFlush方法发送数据(多线程使用的是同一个ctx对象),每次发送的数据也是比较大的数据,在接收的时候,是否会出现数据混乱的情况(一次传输数据过大,会多次调用decode方法,多线程环境下是否会出现问题?),我开50个线程测试时发现if (buf.readableBytes()<buf.getInt(buf.readerIndex()))这句代码报数组越位的异常,请问有什么好的解决办法吗,感谢!

Java多线程并发如何模拟

一个Java Application运行后,在系统中是作为一 个线程吗?运行main方法以后,为什么不能实现多个线程启动?我想用java程序模拟多个消费者和kafka生产者通信,可以实现吗 import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import java.util.Arrays; import java.util.Properties; /** * Created by Administrator on 2016/10/17. */ public class consumerTest extends Thread{ public synchronized void run(){ Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); //消费者组group props.put("group.id", "test"); //是否自动确认offset props.put("enable.auto.commit", "true"); //自动确认offset的时间间隔 props.put("auto.commit.interval.ms", "1000"); //会话超时时间 props.put("session.timeout.ms", "30000"); //key的序列化类 props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); //value的序列化类 props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props); //消费者订阅的topic, 可同时订阅多个 consumer.subscribe(Arrays.asList("test")); while (true) { //读取数据,读取超时时间为100ms ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) System.out.println(String.format("offset = %d, key = %s, value = %s", record.offset(), record.key(), record.value())); } } public static void main(String[] args) { consumerTest test1=new consumerTest(); Thread threads[] = new Thread[5]; for (int i = 0; i < threads.length; i++) threads[i] = new Thread(test1); for (int i = 0; i < threads.length; i++) { threads[i].start(); } } }

关于Netty在项目中的使用-疑惑!

各位好, 小弟有一事不明,请大拿们指点一二! 我想实现一个交易框架,使用netty实现,netty是基于事件的NIO框架,用它做为ServerSocket来处理客户请求,但客户方是用传统的同步BIO来实现的,就是通过socket.connect()这种方式连接到我的netty serverSokcet上来,netty不会保留connection,读完数据就把channel关闭了,connection自然也就不存在了,但client端是同步的需要等待响应,怎么将nettyserver返回的数据同步返回给client呢? 这种场景应该如何实现?请大拿指教!

storm提示connection attempt to Netty-Client-ubuntu1

当我提交任务给storm时,发现2台supervisor中对应的日志输出都如下,请问如何解决: connection attempt 367 to Netty-Client-ubuntu1:6704 failed: java.nio.channels.UnresolvedAddressException b.s.m.n.StormClientHandler [INFO] Connection failed Netty-Client-ubuntu1:6704 java.nio.channels.UnresolvedAddressException at sun.nio.ch.Net.checkAddress(Net.java:101) ~[?:1.8.0_121] at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:622) ~[?:1.8.0_121] at org.apache.storm.shade.org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink.connect(NioClientSocketPipelineSink.java:108) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.socket.nio.NioClientSocketPipelineSink.eventSunk(NioClientSocketPipelineSink.java:70) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendDownstream(DefaultChannelPipeline.java:779) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.handler.codec.oneone.OneToOneEncoder.handleDownstream(OneToOneEncoder.java:54) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.DefaultChannelPipeline.sendDownstream(DefaultChannelPipeline.java:591) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.DefaultChannelPipeline.sendDownstream(DefaultChannelPipeline.java:582) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.Channels.connect(Channels.java:634) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.channel.AbstractChannel.connect(AbstractChannel.java:207) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.bootstrap.ClientBootstrap.connect(ClientBootstrap.java:229) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.bootstrap.ClientBootstrap.connect(ClientBootstrap.java:182) [storm-core-0.10.2.jar:0.10.2] at backtype.storm.messaging.netty.Client$Connect.run(Client.java:518) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:546) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.util.HashedWheelTimer$Worker.notifyExpiredTimeouts(HashedWheelTimer.java:446) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:395) [storm-core-0.10.2.jar:0.10.2] at org.apache.storm.shade.org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [storm-core-0.10.2.jar:0.10.2] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]

java多线程高并发下的oracle数据库异常

代码的功能是生成一个随机的序列化的订单号,正常的情况下一个一个跑没问题,在进行压力测试的时候,多线程高并发下,oracle的create语句就会报错,说是 java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sqlSQLException: ORA-00955: 名称已由现有对象使用 求大神看下。 代码如下: ``` package utils.spring; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import utils.Lang; import javax.sql.DataSource; import java.sql.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 序列发生器(可用于高并发、可回收等场景) * * @author lujijiang * */ @Component @ConfigurationProperties(prefix = "seqGenerator") final public class SequenceGenerator implements InitializingBean { interface Atom<T> { T atom(Connection connection) throws Exception; } public static <T> T atom(Connection connection, Atom<T> atom) throws Exception { connection.setAutoCommit(false); connection .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); try { T obj = atom.atom(connection); connection.commit(); return obj; } catch (Exception e) { connection.rollback(); throw e; } } static Map<String, String> createSqlMap = new ConcurrentHashMap<String, String>(); static { createSqlMap .put("h2", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("mysql", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("informix", "CREATE TABLE %s (v$key DECIMAL(16,0) NOT NULL,v$key$ varchar(256),v$seq DECIMAL(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("oracle", "CREATE TABLE %s (v$key NUMBER(16,0) NOT NULL,v$key$ varchar2(256),v$seq NUMBER(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); } static Map<String, String> insertSqlMap = new ConcurrentHashMap<String, String>(); static { insertSqlMap .put("h2", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("mysql", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("informix", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("oracle", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); } /** * 事务模版 */ TransactionTemplate transactionTemplate; /** * 是否使用新事务 */ boolean newTransaction = true; /** * JDBC模版 */ JdbcTemplate jdbcTemplate; /** * 尝试次数(默认10次) */ int tryTime = 10; /** * 数据库类型 */ String databaseType; /** * 表名 */ private String tableName; /** * 容量 */ private int capacity = 25; /** * 步进 */ private int step = 1; /** * 是否可回收序列号 */ protected boolean recyclable; @Autowired public void setTransactionManager( PlatformTransactionManager transactionManager) { if (transactionManager != null) { transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate .setIsolationLevel(TransactionTemplate.ISOLATION_READ_COMMITTED); transactionTemplate .setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED); } } public boolean isNewTransaction() { return newTransaction; } public void setNewTransaction(boolean newTransaction) { this.newTransaction = newTransaction; } public TransactionTemplate getTransactionTemplate() { return transactionTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setDataSource(DataSource dataSource) { if (jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setTryTime(int tryTime) { this.tryTime = tryTime; } public void setDatabaseType(String databaseType) { if (databaseType != null) { databaseType = databaseType.trim().toLowerCase(); this.databaseType = databaseType; } } public void setTableName(String tableName) { this.tableName = tableName == null ? null : tableName.trim(); } public void setCapacity(int capacity) { this.capacity = capacity; } public void setStep(int step) { this.step = step < 1 ? 1 : step; } public void setRecyclable(boolean recyclable) { this.recyclable = recyclable; } /** * 创建序列 * * @param name * @param length * @param start * @return */ public String generateSequence(String name, int length, long start) { final long key = generateKey(name); try { return generateSequence(key, length, start, name); } catch (Throwable t) { createSequenceTable();//错误就是定位在这里 int time = tryTime >= 0 ? tryTime : 10000; while (time-- > 0) { try { return generateSequence(key, length, start, name); } catch (Throwable e) { } } throw new RuntimeException("Generate sequence failure", t); } } private long generateKey(String name) { return 10000000000L + name.trim().hashCode(); } /** * 创建序列 * * @param key * @param length * @return */ public String generateSequence(String key, int length) { return generateSequence(key, length, 0); } /** * 创建序列 * * @param key * @return */ public String generateSequence(String key) { return generateSequence(key, 6); } private synchronized void createSequenceTable() { try { jdbcTemplate.execute(new ConnectionCallback<Integer>() { public Integer doInConnection(Connection connection) throws SQLException, DataAccessException { ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null); try { while (rs.next()) { return 1; } } finally { rs.close(); } String createSql = String.format( createSqlMap.get(databaseType), tableName); Statement statement = connection.createStatement(); try { statement.execute(createSql);//错误就是定位在这里 } finally { statement.close(); } return 0; } }); } catch (Throwable t) { throw new RuntimeException(t); } } private String generateSequence(final long key, final int length, final long start, final String name) { if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { return atom(connection, new Atom<String>() { @Override public String atom(Connection connection) throws Exception { if (recyclable) { String no = getRecoveredSequence(connection, key, length); if (no != null) { return no; } } Statement statement = connection.createStatement(); try { String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { Long max = rs.getLong(1); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(connection, deleteSql); insertSql = String.format( insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(connection, deleteSql); } return fillLeftZero(max, length); } } finally { rs.close(); } } finally { statement.close(); } throw new IllegalStateException( SequenceGenerator.this.getClass() .getSimpleName() + "无法获取单号,不可能发生的异常"); } }); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } return getTransactionTemplate().execute( new TransactionCallback<String>() { public String doInTransaction(TransactionStatus ts) { try { if (recyclable) { String no = jdbcTemplate .execute(new ConnectionCallback<String>() { public String doInConnection( Connection connection) throws SQLException, DataAccessException { return getRecoveredSequence( connection, key, length); } }); if (no != null) { return no; } } String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name .replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); Long max = jdbcTemplate.queryForObject(querySql, Long.class); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(deleteSql); insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(deleteSql); } return fillLeftZero(max, length); } catch (Throwable t) { ts.isRollbackOnly(); throw new RuntimeException(t); } } }); } /** * 参数化执行SQL * * @param sql * @param args * @return */ protected int execute(String sql, final Object... args) { return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() { public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } }); } /** * 参数化执行SQL * * @param sql * @param args * @return * @throws SQLException */ protected int execute(Connection conn, String sql, final Object... args) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql); try { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } finally { ps.close(); } } protected String fillLeftZero(Long max, int length) { StringBuilder sb = new StringBuilder(); sb.append(max); if (sb.length() >= length) { return sb.substring(sb.length() - length); } else { for (int i = sb.length(); i < length; i++) { sb.insert(0, '0'); } } return sb.toString(); } /** * 获取已回收的序列 * * @param connection * @param key * @throws SQLException */ protected String getRecoveredSequence(Connection connection, long key, int length) throws SQLException { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); try { String querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' for update", tableName, key); statement.executeQuery(querySql); querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' order by v$seq asc", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { try { Long min = rs.getLong(2); rs.updateString(3, "1"); rs.updateRow(); return fillLeftZero(min, length); } catch (Throwable ex) { } } } finally { rs.close(); } } finally { statement.close(); } return null; } /** * 回收序列号 * * @param name * @param sequence */ public void recoveredSequence(final String name, final String sequence) { final long key = generateKey(name); final long seq = Long.valueOf(sequence); if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { atom(connection, new Atom<Object>() { public Object atom(Connection connection) throws Exception { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(connection, updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(connection, insertSql); } return null; } }); connection.commit(); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } else { transactionTemplate.execute(new TransactionCallback<Integer>() { public Integer doInTransaction(TransactionStatus status) { try { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(insertSql); } return null; } catch (Throwable t) { status.isRollbackOnly(); throw new RuntimeException(t); } } }); } } public void afterPropertiesSet() throws Exception { if (this.databaseType == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "databaseType")); } if (databaseType != null) { if (!createSqlMap.containsKey(databaseType)) { throw new IllegalStateException(String.format( "Unsupported database type:%s", databaseType)); } } if (this.jdbcTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' or '%s' is required", "dataSource", "jdbcTemplate")); } if (this.tableName == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "tableName")); } if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*") || tableName.length() > 16) { throw new IllegalStateException(String.format( "Illegal tableName:%s", tableName)); } if (!this.newTransaction) { if (this.transactionTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "transactionManager")); } } } } ``` java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:272) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:202) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:227) at cart.service.service.OrderService.generateOrderNo(OrderService.java:806) at cart.service.service.OrderService.saveVirtualGoodsToOrder(OrderService.java:220) at cart.service.service.OrderService$$FastClassBySpringCGLIB$$19f99be7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at cart.service.service.OrderService$$EnhancerBySpringCGLIB$$feb8eef.saveVirtualGoodsToOrder(<generated>) at cart.service.apiImpl.OrderMainApiImpl.saveVirtualGoodsToOrder(OrderMainApiImpl.java:223) at cart.service.apiImpl.OrderMainApiImpl$$FastClassBySpringCGLIB$$fa3518e.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) at cart.service.apiImpl.OrderMainApiImpl$$EnhancerBySpringCGLIB$$497f044.saveVirtualGoodsToOrder(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.weibo.api.motan.rpc.DefaultProvider.invoke(DefaultProvider.java:57) at com.weibo.api.motan.rpc.AbstractProvider.call(AbstractProvider.java:47) at com.weibo.api.motan.filter.AccessLogFilter.filter(AccessLogFilter.java:56) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at utils.rpc.motan.filter.OpenEntityManagerInMotanFilter.filter(OpenEntityManagerInMotanFilter.java:171) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at com.weibo.api.motan.transport.ProviderMessageRouter.call(ProviderMessageRouter.java:96) at com.weibo.api.motan.transport.ProviderProtectedMessageRouter.call(ProviderProtectedMessageRouter.java:79) at com.weibo.api.motan.transport.ProviderMessageRouter.handle(ProviderMessageRouter.java:91) at com.weibo.api.motan.transport.support.DefaultRpcHeartbeatFactory$HeartMessageHandleWrapper.handle(DefaultRpcHeartbeatFactory.java:82) at com.weibo.api.motan.transport.netty.NettyChannelHandler.processRequest(NettyChannelHandler.java:139) at com.weibo.api.motan.transport.netty.NettyChannelHandler.access$000(NettyChannelHandler.java:47) at com.weibo.api.motan.transport.netty.NettyChannelHandler$1.run(NettyChannelHandler.java:116) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:360) at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:247) ... 39 more Caused by: java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:961) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1726) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1696) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:264) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:247) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:353) ... 40 more

Netty UDP 服务端 运行一段时间后占用CPU使用率很高

Netty UDP 服务端 运行一段时间后占用CPU使用率很高,求解答, public void start() throws Exception { final NioEventLoopGroup group = new NioEventLoopGroup(); try { //启动数据处理线程 new YjInfoHandleThread(yjUserLoginMongodbService); final Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .handler(new ChannelInitializer<NioDatagramChannel>() { @Override public void initChannel(final NioDatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new ServerHandler(yjUserLoginMongodbService)); } }); LOGGER.warn("启动UDP 服务端........................."+port); // Bind and start to accept incoming connections. //InetAddress address = InetAddress.getLocalHost(); // Channel channel= b.bind(address,port).sync().channel(); b.bind(port).sync().channel().closeFuture().await(); } finally { group.shutdownGracefully(); System.out.print("In Server Finally"); } }

web项目嵌入netty客户端报错

正在做一个java web项目,需要与netty服务端通信,就写了一个netty客户端,客户端单独运行 时可以通信,也就是放在main函数里面可以运行,嵌入项目时就报错,不知道是什么原因,求指教!以下是项目中启动客户端代码,netty客户端代码以及报错信息。 ``` 启动代码: NettyClient nc = new NettyClient(); nc.connect(); ``` ``` ``` netty客户端代码: public class NettyClient { public void connect() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new MyClientHandler()); } }); int port=8097; String host="192.168.41.141"; ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } public class MyClientHandler extends ChannelHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) { byte[] send={1,86,1,1}; ByteBuf Bsend =Unpooled.copiedBuffer(send); ctx.writeAndFlush(Bsend); ctx.close(); } public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); } } ``` 报错信息: java.lang.ClassNotFoundException: io.netty.channel.EventLoopGroup at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1335) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1169) at com.gyjy.action.Ldkz.hlkzXF(Ldkz.java:564) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:217) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:184) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:105) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:361) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1080) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:75) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:757) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2287) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) ```

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐