- 浏览: 999800 次
-
文章分类
- 全部博客 (428)
- Hadoop (2)
- HBase (1)
- ELK (1)
- ActiveMQ (13)
- Kafka (5)
- Redis (14)
- Dubbo (1)
- Memcached (5)
- Netty (56)
- Mina (34)
- NIO (51)
- JUC (53)
- Spring (13)
- Mybatis (17)
- MySQL (21)
- JDBC (12)
- C3P0 (5)
- Tomcat (13)
- SLF4J-log4j (9)
- P6Spy (4)
- Quartz (12)
- Zabbix (7)
- JAVA (9)
- Linux (15)
- HTML (9)
- Lucene (0)
- JS (2)
- WebService (1)
- Maven (4)
- Oracle&MSSQL (14)
- iText (11)
- Development Tools (8)
- UTILS (4)
- LIFE (8)
最新评论
-
Donald_Draper:
Donald_Draper 写道刘落落cici 写道能给我发一 ...
DatagramChannelImpl 解析三(多播) -
Donald_Draper:
刘落落cici 写道能给我发一份这个类的源码吗Datagram ...
DatagramChannelImpl 解析三(多播) -
lyfyouyun:
请问楼主,执行消息发送的时候,报错:Transport sch ...
ActiveMQ连接工厂、连接详解 -
ezlhq:
关于 PollArrayWrapper 状态含义猜测:参考 S ...
WindowsSelectorImpl解析一(FdMap,PollArrayWrapper) -
flyfeifei66:
打算使用xmemcache作为memcache的客户端,由于x ...
Memcached分布式客户端(Xmemcached)
netty 通道接口定义:http://donald-draper.iteye.com/blog/2392740
netty 抽象通道初始化:http://donald-draper.iteye.com/blog/2392801
引言:
上一篇文章我们看来netty的抽象通道初始化,先来回顾一下:
抽象通道AbstractChannel内部关联一个硬件底层操作类Unsafe,个事件循环,即通道注册的事件循环EventLoop,一个Channel管道ChannelPipeline,用于存放通道处理器,默认为DefaultChannelPipeline。通道构造主要是初始化通道所属父通道,通道id,底层操作类Unsafe,Channel管道线程,默认的Channel管道线为DefaultChannelPipeline,底层操作类Unsafe为AbstractUnsafe。
抽象通道构造初始化中,初始化底层操作类Unsafe,实际返回的是AbstractUnsafe,
今天我们看一下抽象Unsafe定义:
AbstractUnsafe为抽象通道的内部类
从上面可以看出,抽象Unsafe内部关联一个通道Outbound buf(ChannelOutboundBuffer),
一个接收字节buf分配器Hander( RecvByteBufAllocator.Handle)。
下面几个方法,很容易,一看就明白,不多说了
//AbstractChannel
//AbstractChannel
来看注册通道到事件循环
//注册通道到事件循环
//AbstractChannel
来看实际注册工作:
在实际注册方法中我们有几点要看,
1.
2.
3.
4.
5.
6.
下面分别来看这几点:
1.
2.
//AbstractChannel
3.
4.
//Channel
//AbstractChannel
5.
//AbstractChannel
6.
从上面可以看出,通道注册到事件循环,首先检查事件循环是否为空,通道是否已注册到事件循环,通道是否兼容事件循环,检查通过后,如果线程在当前事件循环,则委托给register0完成实际注册任务,否则创建一个任务线程,完成通道注册事件循环实际工作register0,并将任务线程交由事件循环执行。register0方法首先确保任务没取消,通道打开,调用doRegister完成注册,确保在实际通知注册任务完成前,调用handlerAdded事件,触发通道已注册事件fireChannelRegistered,如果通道激活且第一次注册,则触发通道已激活事件fireChannelActive,否则如果通道配置为自动读取,则读取数据beginRead。这个过程中触发的事件,则传递给通道内部的Channel管道。
再来看绑定
//AbstractChannel
从上面可以看出,地址绑定方法委托给doBind,待子类实现。
再来看如果需要,则关闭通道的方法:
关闭方法我们有几点要关注:
1.
2.
3.
4.
我们分别来看这几点:
1.
2.
//AbstractChannel,待子类实现
3.
//ChannelOutboundBuffer
这个我们单列一篇来讲
4.
//AbstractChannel待子类实现
从上面可以看出,关闭通道方法,首先确保异步关闭任务没有取消,如果Outbound buf为空,则添加异步结果监听器;再次检查关闭任务有没有执行完,执行完则更新异步任务结果;获取关闭线程执行器,如果关闭执行器不为空,则创建关闭任务线程,并由关闭执行器执行,否则在当前事务循环中执行实际关闭任务。实际关闭任务过程为,调用doClose0完成通道关闭任务,待子类实现,然后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf,
如果通道正在刷新,则延迟触发ChannelInactive事件,并反注册,否则直接触发ChannelInactive事件并反注册。
再来通道反注册;
再来看发送数据:
//AbstractChannel
//ChannelOutboundBuffer
从上面可以看出,写消息,首先检查Outbound buf是否为null,为空,则通道关闭,设置任务失败,否则转换消息,估算消息大小,添加写请求消息到OutBound Buf中。
再来看刷新写请求队列
刷新方法有以下几点要看:
1
简单看一下,在下面篇文章我们单讲
//ChannelOutboundBuffer
2.
//AbstractChannel
从上面可以看出,刷新操作,首先将Outbound buf中写请求,添加到刷新队列中,然后将实际刷新工作委托给doWrite,doWrite方法,待子类实现。
再来看断开连接方法:
//AbstractChannel
再来看其他方法:
//包装异常
//AbstractChannel
我们分别来看上述方法中的几点:
1.
2.
//Throwable
总结:
抽象Unsafe内部关联一个通道Outbound buf(ChannelOutboundBuffer),一个接收字节buf分配器Hander( RecvByteBufAllocator.Handle)。
通道注册到事件循环,首先检查事件循环是否为空,通道是否已注册到事件循环,通道是否兼容事件循环,检查通过后,如果线程在当前事件循环,则委托给register0完成实际注册任务,否则创建一个任务线程,完成通道注册事件循环实际工作register0,并将任务线程交由事件循环执行。register0方法首先确保任务没取消,通道打开,调用doRegister完成注册,确保在实际通知注册任务完成前,调用handlerAdded事件,触发通道已注册事件fireChannelRegistered,如果通道激活且第一次注册,则触发通道已激活事件fireChannelActive,否则如果通道配置为自动读取,则读取数据beginRead,实际委托给
doBeginRead方法,待子类实现。这个过程中触发的事件,则传递给通道内部的Channel管道。
地址绑定方法委托给doBind,待子类实现。
关闭通道方法,首先确保异步关闭任务没有取消,如果Outbound buf为空,则添加异步结果监听器;再次检查关闭任务有没有执行完,执行完则更新异步任务结果;获取关闭线程执行器,如果关闭执行器不为空,则创建关闭任务线程,并由关闭执行器执行,否则在当前事务循环中执行实际关闭任务。实际关闭任务过程为,调用doClose0完成通道关闭任务,待子类实现,然后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf,如果通道正在刷新,则延迟触发ChannelInactive事件,并反注册,否则直接触发ChannelInactive事件并反注册。
写消息,首先检查Outbound buf是否为null,为空,则通道关闭,设置任务失败,否则
转换消息,估算消息大小,添加消息到OutBound Buf中。
刷新操作,首先将Outbound buf中写请求,添加到刷新队列中,然后将实际刷新工作委托给doWrite,doWrite方法,待子类实现。
附:
//AbstractChannel
//Throwable
netty 抽象通道初始化:http://donald-draper.iteye.com/blog/2392801
引言:
上一篇文章我们看来netty的抽象通道初始化,先来回顾一下:
抽象通道AbstractChannel内部关联一个硬件底层操作类Unsafe,个事件循环,即通道注册的事件循环EventLoop,一个Channel管道ChannelPipeline,用于存放通道处理器,默认为DefaultChannelPipeline。通道构造主要是初始化通道所属父通道,通道id,底层操作类Unsafe,Channel管道线程,默认的Channel管道线为DefaultChannelPipeline,底层操作类Unsafe为AbstractUnsafe。
抽象通道构造初始化中,初始化底层操作类Unsafe,实际返回的是AbstractUnsafe,
今天我们看一下抽象Unsafe定义:
AbstractUnsafe为抽象通道的内部类
/** * {@link Unsafe} implementation which sub-classes must extend and use. */ protected abstract class AbstractUnsafe implements Unsafe { //通道Outbound buf private volatile ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this); private RecvByteBufAllocator.Handle recvHandle;//接受字节数据分配器Hander private boolean inFlush0;//是否刷新写请求队列数据 /** true if the channel has never been registered, false otherwise */ private boolean neverRegistered = true;//通道是否注册到事件循环 //判断通道是否注册到事件循环 private void assertEventLoop() { assert !registered || eventLoop.inEventLoop(); } }
从上面可以看出,抽象Unsafe内部关联一个通道Outbound buf(ChannelOutboundBuffer),
一个接收字节buf分配器Hander( RecvByteBufAllocator.Handle)。
下面几个方法,很容易,一看就明白,不多说了
//返回接收字节buf分配器Hander @Override public RecvByteBufAllocator.Handle recvBufAllocHandle() { if (recvHandle == null) { //如果为空,则委托给通道的接收字节buf分配器,创建一个Handle recvHandle = config().getRecvByteBufAllocator().newHandle(); } return recvHandle; }
//获取通道Outbound缓冲区 @Override public final ChannelOutboundBuffer outboundBuffer() { return outboundBuffer; }
//获取本地socket地址 @Override public final SocketAddress localAddress() { return localAddress0(); }
//AbstractChannel
/** * Returns the {@link SocketAddress} which is bound locally. 待子类扩展 */ protected abstract SocketAddress localAddress0();
//获取远端socket地址 @Override public final SocketAddress remoteAddress() { return remoteAddress0(); }
//AbstractChannel
/** * Return the {@link SocketAddress} which the {@link Channel} is connected to. 待子类扩展 */ protected abstract SocketAddress remoteAddress0();
来看注册通道到事件循环
//注册通道到事件循环
@Override public final void register(EventLoop eventLoop, final ChannelPromise promise) { //首先检查事件循环是否为空,通道是否已注册到事件循环,通道是否兼容事件循环 if (eventLoop == null) { throw new NullPointerException("eventLoop"); } if (isRegistered()) { promise.setFailure(new IllegalStateException("registered to an event loop already")); return; } if (!isCompatible(eventLoop)) { promise.setFailure( new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName())); return; } AbstractChannel.this.eventLoop = eventLoop; //如果线程在当前事件循环,则委托给register0 if (eventLoop.inEventLoop()) { register0(promise); } else { //否则创建一个任务线程,完成通道注册事件循环实际工作,并将任务线程交由事件循环执行。 try { eventLoop.execute(new Runnable() { @Override public void run() { register0(promise); } }); } catch (Throwable t) { logger.warn( "Force-closing a channel whose registration task was not accepted by an event loop: {}", AbstractChannel.this, t); closeForcibly(); closeFuture.setClosed(); safeSetFailure(promise, t); } } }
//AbstractChannel
/** * Return {@code true} if the given {@link EventLoop} is compatible with this instance. 通道是否兼容事件循环,待子类实现 */ protected abstract boolean isCompatible(EventLoop loop);
来看实际注册工作:
private void register0(ChannelPromise promise) { try { // check if the channel is still open as it could be closed in the mean time when the register // call was outside of the eventLoop //确保任务没取消,通道打开 if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } boolean firstRegistration = neverRegistered; //完成实际注册 doRegister(); neverRegistered = false; registered = true; // Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the // user may already fire events through the pipeline in the ChannelFutureListener. //确保在实际通知注册任务完成前,调用handlerAdded事件 pipeline.invokeHandlerAddedIfNeeded(); //更新注册通道到事件循环成功 safeSetSuccess(promise); //触发通道已注册事件fireChannelRegistered pipeline.fireChannelRegistered(); // Only fire a channelActive if the channel has never been registered. This prevents firing // multiple channel actives if the channel is deregistered and re-registered. if (isActive()) { if (firstRegistration) { //触发通道已激活事件 pipeline.fireChannelActive(); } else if (config().isAutoRead()) { // This channel was registered before and autoRead() is set. This means we need to begin read // again so that we process inbound data. // // See https://github.com/netty/netty/issues/4805 //如果通道配置为自动读取,则读取数据 beginRead(); } } } catch (Throwable t) { // Close the channel directly to avoid FD leak. //异常,则强制关闭通道 closeForcibly(); closeFuture.setClosed();//更新异步关闭任务结果为已关闭 safeSetFailure(promise, t);//设置任务注册失败 } }
在实际注册方法中我们有几点要看,
1.
//确保任务没取消,通道打开 if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } @Deprecated protected final boolean ensureOpen(ChannelPromise promise) { if (isOpen()) { return true; } safeSetFailure(promise, ENSURE_OPEN_CLOSED_CHANNEL_EXCEPTION); return false; }
2.
//完成实际注册 doRegister();
3.
//更新注册通道到事件循环成功 safeSetSuccess(promise);
4.
if (isActive()) { if (firstRegistration) { //触发通道已激活事件 pipeline.fireChannelActive(); } else if (config().isAutoRead()) { // This channel was registered before and autoRead() is set. This means we need to begin read // again so that we process inbound data. // // See https://github.com/netty/netty/issues/4805 //如果通道配置为自动读取,则读取数据 beginRead(); } }
5.
// Close the channel directly to avoid FD leak. //异常,则强制关闭通道 closeForcibly(); closeFuture.setClosed();//更新异步关闭任务结果为已关闭
6.
safeSetFailure(promise, t);//设置任务注册失败
下面分别来看这几点:
1.
//确保任务没取消,通道打开 if (!promise.setUncancellable() || !ensureOpen(promise)) { return; }
@Deprecated protected final boolean ensureOpen(ChannelPromise promise) { if (isOpen()) { return true; } safeSetFailure(promise, ENSURE_OPEN_CLOSED_CHANNEL_EXCEPTION); return false; }
2.
//完成实际注册 doRegister();
//AbstractChannel
/** * Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process. * * Sub-classes may override this method 待子类实现 */ protected void doRegister() throws Exception { // NOOP }
3.
//更新注册通道到事件循环成功 safeSetSuccess(promise);
/** * Marks the specified {@code promise} as success. If the {@code promise} is done already, log a message. */ protected final void safeSetSuccess(ChannelPromise promise) { if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { logger.warn("Failed to mark a promise as success because it is done already: {}", promise); } }
4.
if (isActive()) { if (firstRegistration) { //触发通道已激活事件 pipeline.fireChannelActive(); } else if (config().isAutoRead()) { // This channel was registered before and autoRead() is set. This means we need to begin read // again so that we process inbound data. // // See https://github.com/netty/netty/issues/4805 //如果通道配置为自动读取,则读取数据 beginRead(); } }
//Channel
/** * Return {@code true} if the {@link Channel} is active and so connected. */ boolean isActive();
//如果通道配置为自动读取,则读取数据 beginRead();
@Override public final void beginRead() { assertEventLoop(); if (!isActive()) { return; } try { //实际读取方法 doBeginRead(); } catch (final Exception e) { //否则延后触发异常事件 invokeLater(new Runnable() { @Override public void run() { pipeline.fireExceptionCaught(e); } }); close(voidPromise()); } }
//AbstractChannel
/** * Schedule a read operation. */ protected abstract void doBeginRead() throws Exception;
//否则延后触发异常事件 private void invokeLater(Runnable task) { try { // This method is used by outbound operation implementations to trigger an inbound event later. // They do not trigger an inbound event immediately because an outbound operation might have been // triggered by another inbound event handler method. If fired immediately, the call stack // will look like this for example: // // handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection. // -> handlerA.ctx.close() // -> channel.unsafe.close() // -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet // // which means the execution of two inbound handler methods of the same handler overlap undesirably. eventLoop().execute(task); } catch (RejectedExecutionException e) { logger.warn("Can't invoke task later as EventLoop rejected it", e); } }
5.
// Close the channel directly to avoid FD leak. //异常,则强制关闭通道 closeForcibly(); closeFuture.setClosed();//更新异步关闭任务结果为已关闭
//异常,则强制关闭通道 @Override public final void closeForcibly() { assertEventLoop(); try { doClose(); } catch (Exception e) { logger.warn("Failed to close a channel.", e); } }
//AbstractChannel
/** * Close the {@link Channel} */ protected abstract void doClose() throws Exception;
6.
safeSetFailure(promise, t);//设置任务注册失败
/** * Marks the specified {@code promise} as failure. If the {@code promise} is done already, log a message. */ protected final void safeSetFailure(ChannelPromise promise, Throwable cause) { if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); } }
从上面可以看出,通道注册到事件循环,首先检查事件循环是否为空,通道是否已注册到事件循环,通道是否兼容事件循环,检查通过后,如果线程在当前事件循环,则委托给register0完成实际注册任务,否则创建一个任务线程,完成通道注册事件循环实际工作register0,并将任务线程交由事件循环执行。register0方法首先确保任务没取消,通道打开,调用doRegister完成注册,确保在实际通知注册任务完成前,调用handlerAdded事件,触发通道已注册事件fireChannelRegistered,如果通道激活且第一次注册,则触发通道已激活事件fireChannelActive,否则如果通道配置为自动读取,则读取数据beginRead。这个过程中触发的事件,则传递给通道内部的Channel管道。
再来看绑定
@Override public final void bind(final SocketAddress localAddress, final ChannelPromise promise) { assertEventLoop(); //首先检查绑定任务是否取消,确保通道打开 if (!promise.setUncancellable() || !ensureOpen(promise)) { return; } // See: https://github.com/netty/netty/issues/576 if (Boolean.TRUE.equals(config().getOption(ChannelOption.SO_BROADCAST)) && localAddress instanceof InetSocketAddress && !((InetSocketAddress) localAddress).getAddress().isAnyLocalAddress() && !PlatformDependent.isWindows() && !PlatformDependent.maybeSuperUser()) { // Warn a user about the fact that a non-root user can't receive a // broadcast packet on *nix if the socket is bound on non-wildcard address. //非root用户,不能接受一个广播消息 logger.warn( "A non-root user can't receive a broadcast packet if the socket " + "is not bound to a wildcard address; binding to a non-wildcard " + "address (" + localAddress + ") anyway as requested."); } boolean wasActive = isActive(); try { //委托给doBind doBind(localAddress); } catch (Throwable t) { safeSetFailure(promise, t); closeIfClosed(); return; } if (!wasActive && isActive()) { //通道第一次激活,触发ChannelActive事件 invokeLater(new Runnable() { @Override public void run() { pipeline.fireChannelActive(); } }); } safeSetSuccess(promise); }
//AbstractChannel
/** * Bind the {@link Channel} to the {@link SocketAddress},待子类实现 */ protected abstract void doBind(SocketAddress localAddress) throws Exception;
从上面可以看出,地址绑定方法委托给doBind,待子类实现。
再来看如果需要,则关闭通道的方法:
closeIfClosed();
protected final void closeIfClosed() { //通道打开,则直接返回,否则关闭 if (isOpen()) { return; } close(voidPromise()); }
@Override public final void close(final ChannelPromise promise) { assertEventLoop(); close(promise, CLOSE_CLOSED_CHANNEL_EXCEPTION, CLOSE_CLOSED_CHANNEL_EXCEPTION, false); } private void close(final ChannelPromise promise, final Throwable cause, final ClosedChannelException closeCause, final boolean notify) { //确保异步任务没有取消 if (!promise.setUncancellable()) { return; } final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { // Only needed if no VoidChannelPromise. //如果Outbound buf为空,则添加异步结果监听器 if (!(promise instanceof VoidChannelPromise)) { // This means close() was called before so we just register a listener and return closeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { promise.setSuccess(); } }); } return; } //如果通道关闭任务已完成,则更新异步任务结果 if (closeFuture.isDone()) { // Closed already. safeSetSuccess(promise); return; } final boolean wasActive = isActive(); //到这里,已经不允许添加消息和刷新Outbound Buf this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. //获取关闭线程执行器 Executor closeExecutor = prepareToClose(); if (closeExecutor != null) { //如果执行器不为空,则委托给关闭器,执行关闭任务线程 closeExecutor.execute(new Runnable() { @Override public void run() { try { // Execute the close. //实际关闭工作 doClose0(promise); } finally { // Call invokeLater so closeAndDeregister is executed in the EventLoop again! invokeLater(new Runnable() { @Override public void run() { // Fail all the queued messages //最后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause); //触发ChannelInactive事件,并反注册 fireChannelInactiveAndDeregister(wasActive); } }); } } }); } else { //否则在当前事件循环中执行关闭任务 try { // Close the channel and fail the queued messages in all cases. doClose0(promise);//实际关闭工作 } finally { // Fail all the queued messages. outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause); } if (inFlush0) { //正在刷新,则延迟触发ChannelInactive事件、反注册 invokeLater(new Runnable() { @Override public void run() { fireChannelInactiveAndDeregister(wasActive); } }); } else { //否则,直接触发ChannelInactive事件、反注册 fireChannelInactiveAndDeregister(wasActive); } } }
关闭方法我们有几点要关注:
1.
//获取关闭线程执行器 Executor closeExecutor = prepareToClose()
2.
// Close the channel and fail the queued messages in all cases. doClose0(promise);//实际关闭工作
3.
//最后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause);
4.
//触发ChannelInactive事件,并反注册 fireChannelInactiveAndDeregister(wasActive);
我们分别来看这几点:
1.
//获取关闭线程执行器 Executor closeExecutor = prepareToClose()
/** * Prepares to close the {@link Channel}. If this method returns an {@link Executor}, the * caller must call the {@link Executor#execute(Runnable)} method with a task that calls * {@link #doClose()} on the returned {@link Executor}. If this method returns {@code null}, * {@link #doClose()} must be called from the caller thread. (i.e. {@link EventLoop}) */ protected Executor prepareToClose() { return null; }
2.
// Close the channel and fail the queued messages in all cases. doClose0(promise);//实际关闭工作
private void doClose0(ChannelPromise promise) { try { doClose(); closeFuture.setClosed(); safeSetSuccess(promise); } catch (Throwable t) { closeFuture.setClosed(); safeSetFailure(promise, t); } }
//AbstractChannel,待子类实现
/** * Close the {@link Channel} */ protected abstract void doClose() throws Exception;
3.
//最后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf outboundBuffer.failFlushed(cause, notify); outboundBuffer.close(closeCause);
//ChannelOutboundBuffer
这个我们单列一篇来讲
4.
//触发ChannelInactive事件,并反注册 fireChannelInactiveAndDeregister(wasActive);
private void fireChannelInactiveAndDeregister(final boolean wasActive) { deregister(voidPromise(), wasActive && !isActive()); } private void deregister(final ChannelPromise promise, final boolean fireChannelInactive) { if (!promise.setUncancellable()) { return; } if (!registered) { safeSetSuccess(promise); return; } // As a user may call deregister() from within any method while doing processing in the ChannelPipeline, // we need to ensure we do the actual deregister operation later. This is needed as for example, // we may be in the ByteToMessageDecoder.callDecode(...) method and so still try to do processing in // the old EventLoop while the user already registered the Channel to a new EventLoop. Without delay, // the deregister operation this could lead to have a handler invoked by different EventLoop and so // threads. // // See: // https://github.com/netty/netty/issues/4435 invokeLater(new Runnable() { @Override public void run() { try { //实际反注册 doDeregister(); } catch (Throwable t) { logger.warn("Unexpected exception occurred while deregistering a channel.", t); } finally { //当前通道已失效,则触发ChannelInactive事件 if (fireChannelInactive) { pipeline.fireChannelInactive(); } // Some transports like local and AIO does not allow the deregistration of // an open channel. Their doDeregister() calls close(). Consequently, // close() calls deregister() again - no need to fire channelUnregistered, so check // if it was registered. if (registered) { registered = false; pipeline.fireChannelUnregistered(); } safeSetSuccess(promise); } } }); }
//AbstractChannel待子类实现
/** * Deregister the {@link Channel} from its {@link EventLoop}. * * Sub-classes may override this method */ protected void doDeregister() throws Exception { // NOOP }
从上面可以看出,关闭通道方法,首先确保异步关闭任务没有取消,如果Outbound buf为空,则添加异步结果监听器;再次检查关闭任务有没有执行完,执行完则更新异步任务结果;获取关闭线程执行器,如果关闭执行器不为空,则创建关闭任务线程,并由关闭执行器执行,否则在当前事务循环中执行实际关闭任务。实际关闭任务过程为,调用doClose0完成通道关闭任务,待子类实现,然后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf,
如果通道正在刷新,则延迟触发ChannelInactive事件,并反注册,否则直接触发ChannelInactive事件并反注册。
再来通道反注册;
@Override public final void deregister(final ChannelPromise promise) { assertEventLoop(); deregister(promise, false); }
再来看发送数据:
@Override public final void write(Object msg, ChannelPromise promise) { assertEventLoop(); ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { // If the outboundBuffer is null we know the channel was closed and so // need to fail the future right away. If it is not null the handling of the rest // will be done in flush0() // See https://github.com/netty/netty/issues/2362 //首先检查Outbound buf是否为null,为空,则通道关闭,设置任务失败 safeSetFailure(promise, WRITE_CLOSED_CHANNEL_EXCEPTION); // release message now to prevent resource-leak ReferenceCountUtil.release(msg);//释放消息 return; } int size; try { //转换消息 msg = filterOutboundMessage(msg); //估算消息大小 size = pipeline.estimatorHandle().size(msg); if (size < 0) { size = 0; } } catch (Throwable t) { safeSetFailure(promise, t); ReferenceCountUtil.release(msg); return; } //添加消息到outBound Buf outboundBuffer.addMessage(msg, size, promise); }
//AbstractChannel
/** * Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that * the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer) 转换消息 */ protected Object filterOutboundMessage(Object msg) throws Exception { return msg; }
//ChannelOutboundBuffer
/** * Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once * the message was written. */ public void addMessage(Object msg, int size, ChannelPromise promise) { Entry entry = Entry.newInstance(msg, size, total(msg), promise); if (tailEntry == null) { flushedEntry = null; tailEntry = entry; } else { Entry tail = tailEntry; tail.next = entry; tailEntry = entry; } if (unflushedEntry == null) { unflushedEntry = entry; } // increment pending bytes after adding message to the unflushed arrays. // See https://github.com/netty/netty/issues/1619 incrementPendingOutboundBytes(entry.pendingSize, false); }
从上面可以看出,写消息,首先检查Outbound buf是否为null,为空,则通道关闭,设置任务失败,否则转换消息,估算消息大小,添加写请求消息到OutBound Buf中。
再来看刷新写请求队列
@Override public final void flush() { assertEventLoop(); ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null) { return; } //将Outbound buf中写请求,添加到刷新队列中 outboundBuffer.addFlush(); //刷新Outbound buf flush0(); }
刷新方法有以下几点要看:
1
//将Outbound buf中写请求,添加到刷新队列中 outboundBuffer.addFlush();
简单看一下,在下面篇文章我们单讲
//ChannelOutboundBuffer
/** * Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed * and so you will be able to handle them. */ public void addFlush() { // There is no need to process all entries if there was already a flush before and no new messages // where added in the meantime. // // See https://github.com/netty/netty/issues/2577 Entry entry = unflushedEntry; if (entry != null) { if (flushedEntry == null) { // there is no flushedEntry yet, so start with the entry flushedEntry = entry; } do { flushed ++; if (!entry.promise.setUncancellable()) { // Was cancelled so make sure we free up memory and notify about the freed bytes int pending = entry.cancel(); decrementPendingOutboundBytes(pending, false, true); } entry = entry.next; } while (entry != null); // All flushed so reset unflushedEntry unflushedEntry = null; } }
2.
//刷新Outbound buf flush0();
@SuppressWarnings("deprecation") protected void flush0() { if (inFlush0) { // Avoid re-entrance return; } final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; if (outboundBuffer == null || outboundBuffer.isEmpty()) { return; } inFlush0 = true; // Mark all pending write requests as failure if the channel is inactive. if (!isActive()) { try { if (isOpen()) { outboundBuffer.failFlushed(FLUSH0_NOT_YET_CONNECTED_EXCEPTION, true); } else { // Do not trigger channelWritabilityChanged because the channel is closed already. outboundBuffer.failFlushed(FLUSH0_CLOSED_CHANNEL_EXCEPTION, false); } } finally { inFlush0 = false; } return; } try { //实际刷新Outbound buf doWrite(outboundBuffer); } catch (Throwable t) { if (t instanceof IOException && config().isAutoClose()) { /** * Just call {@link #close(ChannelPromise, Throwable, boolean)} here which will take care of * failing all flushed messages and also ensure the actual close of the underlying transport * will happen before the promises are notified. * * This is needed as otherwise {@link #isActive()} , {@link #isOpen()} and {@link #isWritable()} * may still return {@code true} even if the channel should be closed as result of the exception. */ close(voidPromise(), t, FLUSH0_CLOSED_CHANNEL_EXCEPTION, false); } else { outboundBuffer.failFlushed(t, true); } } finally { inFlush0 = false; } }
//AbstractChannel
/** * Flush the content of the given buffer to the remote peer. */ protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception;
从上面可以看出,刷新操作,首先将Outbound buf中写请求,添加到刷新队列中,然后将实际刷新工作委托给doWrite,doWrite方法,待子类实现。
再来看断开连接方法:
@Override public final void disconnect(final ChannelPromise promise) { assertEventLoop(); if (!promise.setUncancellable()) { return; } boolean wasActive = isActive(); try { //完成实际断开连接 doDisconnect(); } catch (Throwable t) { safeSetFailure(promise, t); closeIfClosed(); return; } if (wasActive && !isActive()) { invokeLater(new Runnable() { @Override public void run() { pipeline.fireChannelInactive(); } }); } safeSetSuccess(promise); closeIfClosed(); // doDisconnect() might have closed the channel }
//AbstractChannel
/** * Disconnect this {@link Channel} from its remote peer 断开连接,待子类扩展 */ protected abstract void doDisconnect() throws Exception;
再来看其他方法:
@Override public final ChannelPromise voidPromise() { assertEventLoop(); return unsafeVoidPromise; }
//包装异常
/** * Appends the remote address to the message of the exceptions caused by connection attempt failure. */ protected final Throwable annotateConnectException(Throwable cause, SocketAddress remoteAddress) { if (cause instanceof ConnectException) {//连接异常 return new AnnotatedConnectException((ConnectException) cause, remoteAddress); } if (cause instanceof NoRouteToHostException) {//无路由异常 return new AnnotatedNoRouteToHostException((NoRouteToHostException) cause, remoteAddress); } if (cause instanceof SocketException) {//socket异常 return new AnnotatedSocketException((SocketException) cause, remoteAddress); } return cause; }
//AbstractChannel
//连接异常 private static final class AnnotatedConnectException extends ConnectException { private static final long serialVersionUID = 3901958112696433556L; AnnotatedConnectException(ConnectException exception, SocketAddress remoteAddress) { //将地址添加到异常信息中 super(exception.getMessage() + ": " + remoteAddress); initCause(exception);//初始化异常 //设置异常堆栈 setStackTrace(exception.getStackTrace()); } //填充异常堆栈 @Override public Throwable fillInStackTrace() { return this; } }
我们分别来看上述方法中的几点:
1.
initCause(exception);//初始化异常
//Throwable /** * Initializes the <i>cause</i> of this throwable to the specified value. * (The cause is the throwable that caused this throwable to get thrown.) * * <p>This method can be called at most once. It is generally called from * within the constructor, or immediately after creating the * throwable. If this throwable was created * with {@link #Throwable(Throwable)} or * {@link #Throwable(String,Throwable)}, this method cannot be called * even once. * * <p>An example of using this method on a legacy throwable type * without other support for setting the cause is: * * <pre> * try { * lowLevelOp(); * } catch (LowLevelException le) { * throw (HighLevelException) * new HighLevelException().initCause(le); // Legacy constructor * } * </pre> * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A {@code null} value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @return a reference to this {@code Throwable} instance. * @throws IllegalArgumentException if {@code cause} is this * throwable. (A throwable cannot be its own cause.) * @throws IllegalStateException if this throwable was * created with {@link #Throwable(Throwable)} or * {@link #Throwable(String,Throwable)}, or this method has already * been called on this throwable. * @since 1.4 */ public synchronized Throwable initCause(Throwable cause) { if (this.cause != this) throw new IllegalStateException("Can't overwrite cause"); if (cause == this) throw new IllegalArgumentException("Self-causation not permitted"); this.cause = cause; return this; }
2.
//填充异常堆栈 @Override public Throwable fillInStackTrace() { return this; }
//Throwable
/** * Fills in the execution stack trace. This method records within this * {@code Throwable} object information about the current state of * the stack frames for the current thread. * * <p>If the stack trace of this {@code Throwable} {@linkplain * Throwable#Throwable(String, Throwable, boolean, boolean) is not * writable}, calling this method has no effect. * * @return a reference to this {@code Throwable} instance. * @see java.lang.Throwable#printStackTrace() */ public synchronized Throwable fillInStackTrace() { if (stackTrace != null || backtrace != null /* Out of protocol state */ ) { fillInStackTrace(0); stackTrace = UNASSIGNED_STACK; } return this; } private native Throwable fillInStackTrace(int dummy);
总结:
抽象Unsafe内部关联一个通道Outbound buf(ChannelOutboundBuffer),一个接收字节buf分配器Hander( RecvByteBufAllocator.Handle)。
通道注册到事件循环,首先检查事件循环是否为空,通道是否已注册到事件循环,通道是否兼容事件循环,检查通过后,如果线程在当前事件循环,则委托给register0完成实际注册任务,否则创建一个任务线程,完成通道注册事件循环实际工作register0,并将任务线程交由事件循环执行。register0方法首先确保任务没取消,通道打开,调用doRegister完成注册,确保在实际通知注册任务完成前,调用handlerAdded事件,触发通道已注册事件fireChannelRegistered,如果通道激活且第一次注册,则触发通道已激活事件fireChannelActive,否则如果通道配置为自动读取,则读取数据beginRead,实际委托给
doBeginRead方法,待子类实现。这个过程中触发的事件,则传递给通道内部的Channel管道。
地址绑定方法委托给doBind,待子类实现。
关闭通道方法,首先确保异步关闭任务没有取消,如果Outbound buf为空,则添加异步结果监听器;再次检查关闭任务有没有执行完,执行完则更新异步任务结果;获取关闭线程执行器,如果关闭执行器不为空,则创建关闭任务线程,并由关闭执行器执行,否则在当前事务循环中执行实际关闭任务。实际关闭任务过程为,调用doClose0完成通道关闭任务,待子类实现,然后设置刷新Outbound 写请求队列数据失败,关闭OutBound buf,如果通道正在刷新,则延迟触发ChannelInactive事件,并反注册,否则直接触发ChannelInactive事件并反注册。
写消息,首先检查Outbound buf是否为null,为空,则通道关闭,设置任务失败,否则
转换消息,估算消息大小,添加消息到OutBound Buf中。
刷新操作,首先将Outbound buf中写请求,添加到刷新队列中,然后将实际刷新工作委托给doWrite,doWrite方法,待子类实现。
附:
//AbstractChannel
private static final class AnnotatedNoRouteToHostException extends NoRouteToHostException { private static final long serialVersionUID = -6801433937592080623L; AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); setStackTrace(exception.getStackTrace()); } @Override public Throwable fillInStackTrace() { return this; } } private static final class AnnotatedSocketException extends SocketException { private static final long serialVersionUID = 3896743275010454039L; AnnotatedSocketException(SocketException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); setStackTrace(exception.getStackTrace()); } @Override public Throwable fillInStackTrace() { return this; } }
//Throwable
public class Throwable implements Serializable { /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -3042686055658047285L; /** * Native code saves some indication of the stack backtrace in this slot. */ private transient Object backtrace; /** * Specific details about the Throwable. For example, for * {@code FileNotFoundException}, this contains the name of * the file that could not be found. 异常消息 * * @serial */ private String detailMessage; /** * Holder class to defer initializing sentinel objects only used * for serialization. */ private static class SentinelHolder { /** * {@linkplain #setStackTrace(StackTraceElement[]) Setting the * stack trace} to a one-element array containing this sentinel * value indicates future attempts to set the stack trace will be * ignored. The sentinal is equal to the result of calling:<br> * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)} */ public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL = new StackTraceElement("", "", null, Integer.MIN_VALUE); /** * Sentinel value used in the serial form to indicate an immutable * stack trace. */ public static final StackTraceElement[] STACK_TRACE_SENTINEL = new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL}; } /** * A shared value for an empty stack. 异常堆栈 */ private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0]; /* * To allow Throwable objects to be made immutable and safely * reused by the JVM, such as OutOfMemoryErrors, fields of * Throwable that are writable in response to user actions, cause, * stackTrace, and suppressedExceptions obey the following * protocol: * * 1) The fields are initialized to a non-null sentinel value * which indicates the value has logically not been set. * * 2) Writing a null to the field indicates further writes * are forbidden * * 3) The sentinel value may be replaced with another non-null * value. * * For example, implementations of the HotSpot JVM have * preallocated OutOfMemoryError objects to provide for better * diagnosability of that situation. These objects are created * without calling the constructor for that class and the fields * in question are initialized to null. To support this * capability, any new fields added to Throwable that require * being initialized to a non-null value require a coordinated JVM * change. */ /** * The throwable that caused this throwable to get thrown, or null if this * throwable was not caused by another throwable, or if the causative * throwable is unknown. If this field is equal to this throwable itself, * it indicates that the cause of this throwable has not yet been * initialized. *异常原因 * @serial * @since 1.4 */ private Throwable cause = this; /** * The stack trace, as returned by {@link #getStackTrace()}. * * The field is initialized to a zero-length array. A {@code * null} value of this field indicates subsequent calls to {@link * #setStackTrace(StackTraceElement[])} and {@link * #fillInStackTrace()} will be be no-ops. *异常堆栈 * @serial * @since 1.4 */ private StackTraceElement[] stackTrace = UNASSIGNED_STACK; // Setting this static field introduces an acceptable // initialization dependency on a few java.util classes. private static final List<Throwable> SUPPRESSED_SENTINEL = Collections.unmodifiableList(new ArrayList<Throwable>(0)); /** * The list of suppressed exceptions, as returned by {@link * #getSuppressed()}. The list is initialized to a zero-element * unmodifiable sentinel list. When a serialized Throwable is * read in, if the {@code suppressedExceptions} field points to a * zero-element list, the field is reset to the sentinel value. * * @serial * @since 1.7 */ private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL; /** Message for trying to suppress a null exception. */ private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception."; /** Message for trying to suppress oneself. */ private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted"; /** Caption for labeling causative exception stack traces */ private static final String CAUSE_CAPTION = "Caused by: "; /** Caption for labeling suppressed exception stack traces */ private static final String SUPPRESSED_CAPTION = "Suppressed: "; /** * Constructs a new throwable with {@code null} as its detail message. * The cause is not initialized, and may subsequently be initialized by a * call to {@link #initCause}. * * <p>The {@link #fillInStackTrace()} method is called to initialize * the stack trace data in the newly created throwable. */ public Throwable() { fillInStackTrace(); } ... }
发表评论
-
netty NioSocketChannel解析
2017-09-29 12:50 1369netty 抽象BootStrap定义:http://dona ... -
netty Pooled字节buf分配器
2017-09-28 13:00 2099netty 字节buf定义:http://donald-dra ... -
netty Unpooled字节buf分配器
2017-09-26 22:01 2501netty 字节buf定义:http://donald-dra ... -
netty 抽象字节buf分配器
2017-09-26 08:43 1348netty 字节buf定义:http:// ... -
netty 复合buf概念
2017-09-25 22:31 1348netty 字节buf定义:http://donald-dra ... -
netty 抽象字节buf引用计数器
2017-09-22 12:48 1627netty 字节buf定义:http://donald-dra ... -
netty 抽象字节buf解析
2017-09-22 09:00 1877netty 通道接口定义:http://donald-drap ... -
netty 资源泄漏探测器
2017-09-21 09:37 1440netty 通道接口定义:http://donald-drap ... -
netty 字节buf定义
2017-09-20 08:31 2880netty 通道接口定义:http://donald-drap ... -
netty 默认通道配置后续
2017-09-18 08:36 2225netty 通道接口定义:http://donald-drap ... -
netty 默认通道配置初始化
2017-09-17 22:51 2070netty 通道接口定义:http://donald-drap ... -
netty 通道配置接口定义
2017-09-17 14:51 1119netty 通道接口定义:http://donald-drap ... -
netty NioServerSocketChannel解析
2017-09-16 13:01 1910netty ServerBootStrap解析:http:// ... -
netty 抽象nio消息通道
2017-09-15 15:30 1257netty 通道接口定义:http:/ ... -
netty 抽象nio字节通道
2017-09-14 22:39 1243netty 通道接口定义:http:/ ... -
netty 抽象nio通道解析
2017-09-14 17:23 992netty 通道接口定义:http://donald-drap ... -
netty 抽象通道后续
2017-09-13 22:40 1335netty Inboudn/Outbound通道Inv ... -
netty 通道Outbound缓冲区
2017-09-13 14:31 2221netty 通道接口定义:http:/ ... -
netty 抽象通道初始化
2017-09-11 12:56 1897netty 管道线定义-ChannelPipeline:htt ... -
netty 通道接口定义
2017-09-10 15:36 1929netty Inboudn/Outbound通道Invoker ...
相关推荐
`AbstractByteBuf`类进一步扩展了`ByteBuf`抽象类的功能,它实现了大部分`ByteBuf`接口中定义的方法,减少了具体实现类的工作量。`AbstractByteBuf`还包含了一些内部状态的管理逻辑,比如当前读指针和写指针的位置。...
5. **UnSafe 系列类**: 这是Netty内部的优化机制,`AbstractNioUnsafe`是`NioSocketChannel`和`NioServerSocketChannel`中使用的抽象类,它提供了一些低级别的I/O操作,如读写数据和关闭通道。`...
Delphi 12.3控件之TraeSetup-stable-1.0.12120.exe
基于GPRS,GPS的电动汽车远程监控系统的设计与实现.pdf
内容概要:本文详细介绍了如何利用MATLAB/Simulink 2018a进行单机无穷大系统的暂态稳定性仿真。主要内容包括搭建同步发电机模型、设置无穷大系统等效电源、配置故障模块及其控制信号、优化求解器设置以及绘制和分析转速波形和摇摆曲线。文中还提供了多个实用脚本,如故障类型切换、摇摆曲线计算和极限切除角的求解方法。此外,作者分享了一些实践经验,如避免常见错误和提高仿真效率的小技巧。 适合人群:从事电力系统研究和仿真的工程师和技术人员,尤其是对MATLAB/Simulink有一定基础的用户。 使用场景及目标:适用于需要进行电力系统暂态稳定性分析的研究项目或工程应用。主要目标是帮助用户掌握单机无穷大系统的建模和仿真方法,理解故障对系统稳定性的影响,并能够通过仿真结果评估系统的性能。 其他说明:文中提到的一些具体操作和脚本代码对于初学者来说可能会有一定的难度,建议结合官方文档或其他教程一起学习。同时,部分技巧和经验来自于作者的实际操作,具有一定的实用性。
KUKA机器人相关资料
基于DLR模型的PM10–能见度–湿度相关性 研究.pdf
内容概要:本文详细介绍了如何使用MATLAB/Simulink进行光伏并网系统的最大功率点跟踪(MPPT)仿真,重点讨论了电导增量法的应用。首先阐述了电导增量法的基本原理,接着展示了如何在Simulink中构建光伏电池模型和MPPT控制系统,包括Boost升压电路的设计和PI控制参数的设定。随后,通过仿真分析了不同光照强度和温度条件对光伏系统性能的影响,验证了电导增量法的有效性,并提出了针对特定工况的优化措施。 适合人群:从事光伏系统研究和技术开发的专业人士,尤其是那些希望通过仿真工具深入理解MPPT控制机制的人群。 使用场景及目标:适用于需要评估和优化光伏并网系统性能的研发项目,旨在提高系统在各种环境条件下的最大功率点跟踪效率。 其他说明:文中提供了详细的代码片段和仿真结果图表,帮助读者更好地理解和复现实验过程。此外,还提到了一些常见的仿真陷阱及解决方案,如变步长求解器的问题和PI参数整定技巧。
KUKA机器人相关文档
内容概要:本文详细探讨了双馈风力发电机(DFIG)在Simulink环境下的建模方法及其在不同风速条件下的电流与电压波形特征。首先介绍了DFIG的基本原理,即定子直接接入电网,转子通过双向变流器连接电网的特点。接着阐述了Simulink模型的具体搭建步骤,包括风力机模型、传动系统模型、DFIG本体模型和变流器模型的建立。文中强调了变流器控制算法的重要性,特别是在应对风速变化时,通过实时调整转子侧的电压和电流,确保电流和电压波形的良好特性。此外,文章还讨论了模型中的关键技术和挑战,如转子电流环控制策略、低电压穿越性能、直流母线电压脉动等问题,并提供了具体的解决方案和技术细节。最终,通过对故障工况的仿真测试,验证了所建模型的有效性和优越性。 适用人群:从事风力发电研究的技术人员、高校相关专业师生、对电力电子控制系统感兴趣的工程技术人员。 使用场景及目标:适用于希望深入了解DFIG工作原理、掌握Simulink建模技能的研究人员;旨在帮助读者理解DFIG在不同风速条件下的动态响应机制,为优化风力发电系统的控制策略提供理论依据和技术支持。 其他说明:文章不仅提供了详细的理论解释,还附有大量Matlab/Simulink代码片段,便于读者进行实践操作。同时,针对一些常见问题给出了实用的调试技巧,有助于提高仿真的准确性和可靠性。
linux之用户管理教程.md
内容概要:本文详细介绍了利用三菱PLC(特别是FX系列)和组态王软件构建3x3书架式堆垛式立体库的方法。首先阐述了IO分配的原则,明确了输入输出信号的功能,如仓位检测、堆垛机运动控制等。接着深入解析了梯形图编程的具体实现,包括基本的左右移动控制、复杂的自动寻址逻辑,以及确保安全性的限位保护措施。还展示了接线图和原理图的作用,强调了正确的电气连接方式。最后讲解了组态王的画面设计技巧,通过图形化界面实现对立体库的操作和监控。 适用人群:从事自动化仓储系统设计、安装、调试的技术人员,尤其是熟悉三菱PLC和组态王的工程师。 使用场景及目标:适用于需要提高仓库空间利用率的小型仓储环境,旨在帮助技术人员掌握从硬件选型、电路设计到软件编程的全流程技能,最终实现高效稳定的自动化仓储管理。 其他说明:文中提供了多个实用的编程技巧和注意事项,如避免常见错误、优化性能参数等,有助于减少实际应用中的故障率并提升系统的可靠性。
基于STM32的循迹避障小车 主控:STM32 显示:OLED 电源模块 舵机云台 超声波测距 红外循迹模块(3个,左中右) 蓝牙模块 按键(6个,模式和手动控制小车状态) TB6612驱动的双电机 功能: 该小车共有3种模式: 自动模式:根据红外循迹和超声波测距模块决定小车的状态 手动模式:根据按键的状态来决定小车的状态 蓝牙模式:根据蓝牙指令来决定小车的状态 自动模式: 自动模式下,检测距离低于5cm小车后退 未检测到任何黑线,小车停止 检测到左边或左边+中间黑线,小车左转 检测到右边或右边+中间黑线,小车右转 检测到中边或左边+中间+右边黑线,小车前进 手动模式:根据按键的状态来决定小车的状态 蓝牙模式: //需切换为蓝牙模式才能指令控制 *StatusX X取值为0-4 0:小车停止 1:小车前进 2:小车后退 3:小车左转 4:小车右转
矢量边界,行政区域边界,精确到乡镇街道,可直接导入arcgis使用
内容概要:本文探讨了基于IEEE33节点的主动配电网优化方法,旨在通过合理的调度模型降低配电网的总运行成本。文中详细介绍了模型的构建,包括风光发电、储能装置、柴油发电机和燃气轮机等多种分布式电源的集成。为了实现这一目标,作者提出了具体的约束条件,如储能充放电功率限制和潮流约束,并采用了粒子群算法进行求解。通过一系列实验验证,最终得到了优化的分布式电源运行计划,显著降低了总成本并提高了系统的稳定性。 适合人群:从事电力系统优化、智能电网研究的专业人士和技术爱好者。 使用场景及目标:适用于需要优化配电网运行成本的研究机构和企业。主要目标是在满足各种约束条件下,通过合理的调度策略使配电网更加经济高效地运行。 其他说明:文章不仅提供了详细的理论推导和算法实现,还分享了许多实用的经验技巧,如储能充放电策略、粒子群算法参数选择等。此外,通过具体案例展示了不同电源之间的协同作用及其经济效益。
KUKA机器人相关文档
内容概要:本文详细介绍了将光热电站(CSP)和有机朗肯循环(ORC)集成到综合能源系统中的优化建模方法。主要内容涵盖系统的目标函数设计、关键设备的约束条件(如CSP储热罐、ORC热电耦合)、以及具体实现的技术细节。文中通过MATLAB和YALMIP工具进行建模,采用CPLEX求解器解决混合整数规划问题,确保系统在经济性和环境效益方面的最优表现。此外,文章还讨论了碳排放惩罚机制、风光弃能处理等实际应用场景中的挑战及其解决方案。 适合人群:从事综合能源系统研究的专业人士,尤其是对光热发电、余热利用感兴趣的科研工作者和技术开发者。 使用场景及目标:适用于需要评估和优化包含多种能源形式(如光伏、风电、燃气锅炉等)在内的复杂能源系统的项目。目标是在满足供电供热需求的同时,最小化运行成本并减少碳排放。 其他说明:文中提供了大量具体的MATLAB代码片段作为实例,帮助读者更好地理解和复现所提出的优化模型。对于初学者而言,建议从简单的确定性模型入手,逐渐过渡到更复杂的随机规划和鲁棒优化。
网站设计与管理作业一.ppt
内容概要:本文详细介绍了如何使用MATLAB搭建双闭环Buck电路的仿真模型。首先定义了主电路的关键参数,如输入电压、电感、电容等,并解释了这些参数的选择依据。接着分别对电压外环和电流内环进行了PI控制器的设计,强调了电流环响应速度需要显著高于电压环以确保系统的稳定性。文中还讨论了仿真过程中的一些关键技术细节,如PWM死区时间的设置、低通滤波器的应用以及参数调整的方法。通过对比单闭环和双闭环系统的性能,展示了双闭环方案在应对负载突变时的优势。最后分享了一些调试经验和常见问题的解决方案。 适合人群:从事电力电子、电源设计领域的工程师和技术人员,尤其是有一定MATLAB基础的读者。 使用场景及目标:适用于需要进行电源管理芯片设计验证、电源系统性能评估的研究人员和工程师。主要目标是提高电源系统的稳定性和响应速度,特别是在负载变化剧烈的情况下。 其他说明:文章不仅提供了详细的理论分析,还包括了大量的代码片段和具体的调试步骤,帮助读者更好地理解和应用所学知识。同时提醒读者注意仿真与实际情况之间的差异,鼓励在实践中不断探索和改进。
内容概要:本文详细探讨了MATLAB环境下冷热电气多能互补微能源网的鲁棒优化调度模型。首先介绍了多能耦合元件(如风电、光伏、P2G、燃气轮机等)的运行特性模型,展示了如何通过MATLAB代码模拟这些元件的实际运行情况。接着阐述了电、热、冷、气四者的稳态能流模型及其相互关系,特别是热电联产过程中能流的转换和流动。然后重点讨论了考虑经济成本和碳排放最优的优化调度模型,利用MATLAB优化工具箱求解多目标优化问题,确保各能源设备在合理范围内运行并保持能流平衡。最后分享了一些实际应用中的经验和技巧,如处理风光出力预测误差、非线性约束、多能流耦合等。 适合人群:从事能源系统研究、优化调度、MATLAB编程的专业人士和技术爱好者。 使用场景及目标:适用于希望深入了解综合能源系统优化调度的研究人员和工程师。目标是掌握如何在MATLAB中构建和求解复杂的多能互补优化调度模型,提高能源利用效率,降低碳排放。 其他说明:文中提供了大量MATLAB代码片段,帮助读者更好地理解和实践所介绍的内容。此外,还提及了一些有趣的发现和挑战,如多能流耦合的复杂性、鲁棒优化的应用等。