This commit is contained in:
Redkale
2018-01-30 11:27:14 +08:00
parent 11d8d36c12
commit 15cd16e771
13 changed files with 53 additions and 30 deletions

View File

@@ -43,7 +43,7 @@ public class NodeHttpServer extends NodeServer {
} }
private static Server createServer(Application application, AnyValue serconf) { private static Server createServer(Application application, AnyValue serconf) {
return new HttpServer(application.getStartTime()); return new HttpServer(application.getStartTime(), application.getResourceFactory().createChild());
} }
public HttpServer getHttpServer() { public HttpServer getHttpServer() {
@@ -205,10 +205,6 @@ public class NodeHttpServer extends NodeServer {
loadRestServlet(webSocketFilter, restConf, restedObjects, sb); loadRestServlet(webSocketFilter, restConf, restedObjects, sb);
} }
} }
resourceFactory.inject(this.httpServer.getPrepareServlet(), this);
for (HttpRender render : this.httpServer.getHttpRenders()) {
resourceFactory.inject(render, this);
}
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString().trim()); if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString().trim());
} }

View File

@@ -90,8 +90,8 @@ public abstract class NodeServer {
public NodeServer(Application application, Server server) { public NodeServer(Application application, Server server) {
this.application = application; this.application = application;
this.resourceFactory = application.getResourceFactory().createChild();
this.server = server; this.server = server;
this.resourceFactory = server.getResourceFactory();
this.logger = Logger.getLogger(this.getClass().getSimpleName()); this.logger = Logger.getLogger(this.getClass().getSimpleName());
this.serverClassLoader = new RedkaleClassLoader(application.getServerClassLoader()); this.serverClassLoader = new RedkaleClassLoader(application.getServerClassLoader());
Thread.currentThread().setContextClassLoader(this.serverClassLoader); Thread.currentThread().setContextClassLoader(this.serverClassLoader);

View File

@@ -44,7 +44,7 @@ public class NodeSncpServer extends NodeServer {
} }
private static Server createServer(Application application, AnyValue serconf) { private static Server createServer(Application application, AnyValue serconf) {
return new SncpServer(application.getStartTime()); return new SncpServer(application.getStartTime(), application.getResourceFactory().createChild());
} }
@Override @Override

View File

@@ -71,8 +71,11 @@ public class Context {
//JSON操作工厂 //JSON操作工厂
protected final JsonFactory jsonFactory; protected final JsonFactory jsonFactory;
//依赖注入工厂类
protected final ResourceFactory resourceFactory;
public Context(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool, ObjectPool<Response> responsePool, public Context(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool, ObjectPool<Response> responsePool,
final int maxbody, Charset charset, InetSocketAddress address, final PrepareServlet prepare, final int readTimeoutSecond, final int writeTimeoutSecond) { final int maxbody, Charset charset, InetSocketAddress address, ResourceFactory resourceFactory, final PrepareServlet prepare, final int readTimeoutSecond, final int writeTimeoutSecond) {
this.serverStartTime = serverStartTime; this.serverStartTime = serverStartTime;
this.logger = logger; this.logger = logger;
this.executor = executor; this.executor = executor;
@@ -83,12 +86,17 @@ public class Context {
this.charset = UTF8.equals(charset) ? null : charset; this.charset = UTF8.equals(charset) ? null : charset;
this.address = address; this.address = address;
this.prepare = prepare; this.prepare = prepare;
this.resourceFactory = resourceFactory;
this.readTimeoutSecond = readTimeoutSecond; this.readTimeoutSecond = readTimeoutSecond;
this.writeTimeoutSecond = writeTimeoutSecond; this.writeTimeoutSecond = writeTimeoutSecond;
this.jsonFactory = JsonFactory.root(); this.jsonFactory = JsonFactory.root();
this.bsonFactory = BsonFactory.root(); this.bsonFactory = BsonFactory.root();
} }
public ResourceFactory getResourceFactory() {
return resourceFactory;
}
public int getMaxbody() { public int getMaxbody() {
return maxbody; return maxbody;
} }

View File

@@ -45,6 +45,9 @@ public abstract class Server<K extends Serializable, C extends Context, R extend
//应用层协议名 //应用层协议名
protected final String protocol; protected final String protocol;
//依赖注入工厂类
protected final ResourceFactory resourceFactory;
//服务的根Servlet //服务的根Servlet
protected final PrepareServlet<K, C, R, P, S> prepare; protected final PrepareServlet<K, C, R, P, S> prepare;
@@ -93,9 +96,10 @@ public abstract class Server<K extends Serializable, C extends Context, R extend
//最大连接数 //最大连接数
protected int maxconns; protected int maxconns;
protected Server(long serverStartTime, String protocol, PrepareServlet<K, C, R, P, S> servlet) { protected Server(long serverStartTime, String protocol, ResourceFactory resourceFactory, PrepareServlet<K, C, R, P, S> servlet) {
this.serverStartTime = serverStartTime; this.serverStartTime = serverStartTime;
this.protocol = protocol; this.protocol = protocol;
this.resourceFactory = resourceFactory;
this.prepare = servlet; this.prepare = servlet;
} }
@@ -148,6 +152,10 @@ public abstract class Server<K extends Serializable, C extends Context, R extend
this.prepare.destroy(context, config); this.prepare.destroy(context, config);
} }
public ResourceFactory getResourceFactory() {
return resourceFactory;
}
public ThreadPoolExecutor getExecutor() { public ThreadPoolExecutor getExecutor() {
return executor; return executor;
} }

View File

@@ -32,10 +32,10 @@ public class HttpContext extends Context {
protected final ConcurrentHashMap<Class, Creator> asyncHandlerCreators = new ConcurrentHashMap<>(); protected final ConcurrentHashMap<Class, Creator> asyncHandlerCreators = new ConcurrentHashMap<>();
public HttpContext(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool, public HttpContext(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool,
ObjectPool<Response> responsePool, int maxbody, Charset charset, InetSocketAddress address, PrepareServlet prepare, ObjectPool<Response> responsePool, int maxbody, Charset charset, InetSocketAddress address, ResourceFactory resourceFactory, PrepareServlet prepare,
int readTimeoutSecond, int writeTimeoutSecond) { int readTimeoutSecond, int writeTimeoutSecond) {
super(serverStartTime, logger, executor, bufferCapacity, bufferPool, responsePool, maxbody, charset, super(serverStartTime, logger, executor, bufferCapacity, bufferPool, responsePool, maxbody, charset,
address, prepare, readTimeoutSecond, writeTimeoutSecond); address, resourceFactory, prepare, readTimeoutSecond, writeTimeoutSecond);
random.setSeed(Math.abs(System.nanoTime())); random.setSeed(Math.abs(System.nanoTime()));
} }

View File

@@ -230,6 +230,7 @@ public class HttpPrepareServlet extends PrepareServlet<String, HttpContext, Http
this.resourceHttpServlet = new HttpResourceServlet(); this.resourceHttpServlet = new HttpResourceServlet();
logger.log(Level.WARNING, "init HttpResourceSerlvet(" + resServlet + ") error", e); logger.log(Level.WARNING, "init HttpResourceSerlvet(" + resServlet + ") error", e);
} }
context.getResourceFactory().inject(this.resourceHttpServlet);
this.resourceHttpServlet.init(context, resConfig); this.resourceHttpServlet.init(context, resConfig);
} }
{ //设置TemplateEngine { //设置TemplateEngine
@@ -242,6 +243,8 @@ public class HttpPrepareServlet extends PrepareServlet<String, HttpContext, Http
for (HttpRender one : renders) { for (HttpRender one : renders) {
if (one.getType().equals(render.getType())) throw new RuntimeException("HttpRender(" + renderType + ") repeat"); if (one.getType().equals(render.getType())) throw new RuntimeException("HttpRender(" + renderType + ") repeat");
} }
context.getResourceFactory().inject(render);
render.init(context, renderConfig);
renders.add(render); renders.add(render);
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.WARNING, "init HttpRender(" + renderType + ") error", e); logger.log(Level.WARNING, "init HttpRender(" + renderType + ") error", e);

View File

@@ -27,11 +27,15 @@ import org.redkale.util.*;
public class HttpServer extends Server<String, HttpContext, HttpRequest, HttpResponse, HttpServlet> { public class HttpServer extends Server<String, HttpContext, HttpRequest, HttpResponse, HttpServlet> {
public HttpServer() { public HttpServer() {
this(System.currentTimeMillis()); this(System.currentTimeMillis(), ResourceFactory.root());
} }
public HttpServer(long serverStartTime) { public HttpServer(ResourceFactory resourceFactory) {
super(serverStartTime, "TCP", new HttpPrepareServlet()); this(System.currentTimeMillis(), resourceFactory);
}
public HttpServer(long serverStartTime, ResourceFactory resourceFactory) {
super(serverStartTime, "TCP", resourceFactory, new HttpPrepareServlet());
} }
@Override @Override
@@ -369,7 +373,7 @@ public class HttpServer extends Server<String, HttpContext, HttpRequest, HttpRes
AtomicLong cycleResponseCounter = new AtomicLong(); AtomicLong cycleResponseCounter = new AtomicLong();
ObjectPool<Response> responsePool = HttpResponse.createPool(createResponseCounter, cycleResponseCounter, this.responsePoolSize, null); ObjectPool<Response> responsePool = HttpResponse.createPool(createResponseCounter, cycleResponseCounter, this.responsePoolSize, null);
HttpContext httpcontext = new HttpContext(this.serverStartTime, this.logger, executor, rcapacity, bufferPool, responsePool, HttpContext httpcontext = new HttpContext(this.serverStartTime, this.logger, executor, rcapacity, bufferPool, responsePool,
this.maxbody, this.charset, this.address, this.prepare, this.readTimeoutSecond, this.writeTimeoutSecond); this.maxbody, this.charset, this.address, this.resourceFactory, this.prepare, this.readTimeoutSecond, this.writeTimeoutSecond);
responsePool.setCreator((Object... params) -> new HttpResponse(httpcontext, new HttpRequest(httpcontext, addrHeader), addHeaders, setHeaders, defCookie, options, ((HttpPrepareServlet) prepare).renders)); responsePool.setCreator((Object... params) -> new HttpResponse(httpcontext, new HttpRequest(httpcontext, addrHeader), addHeaders, setHeaders, defCookie, options, ((HttpPrepareServlet) prepare).renders));
return httpcontext; return httpcontext;
} }

View File

@@ -431,7 +431,7 @@ public final class Rest {
int index = -1; int index = -1;
for (Map.Entry<String, Parameter> en : paramap.entrySet()) { for (Map.Entry<String, Parameter> en : paramap.entrySet()) {
mv.visitInsn(DUP); mv.visitInsn(DUP);
mv.visitInsn(++index); pushInt(mv, ++index);
mv.visitLdcInsn(en.getKey()); mv.visitLdcInsn(en.getKey());
mv.visitInsn(AASTORE); mv.visitInsn(AASTORE);
} }
@@ -456,7 +456,6 @@ public final class Rest {
} }
mv.visitInsn(ARETURN); mv.visitInsn(ARETURN);
mv.visitLabel(l1); mv.visitLabel(l1);
mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null);
} }
mv.visitInsn(ACONST_NULL); mv.visitInsn(ACONST_NULL);
mv.visitInsn(ARETURN); mv.visitInsn(ARETURN);

View File

@@ -105,7 +105,7 @@ public class WebSocketEngine {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
getLocalWebSockets().stream().filter(x -> (now - x.getLastSendTime()) > intervalms).forEach(x -> x.sendPing()); getLocalWebSockets().stream().filter(x -> (now - x.getLastSendTime()) > intervalms).forEach(x -> x.sendPing());
}, delay, liveinterval, TimeUnit.SECONDS); }, delay, liveinterval, TimeUnit.SECONDS);
if (logger.isLoggable(Level.FINEST)) logger.finest(this.getClass().getSimpleName() + "(" + engineid + ")" + " start keeplive(delay:" + delay + ", wsmaxconns:" + wsmaxconns + ", interval:" + liveinterval + "s) scheduler executor"); if (logger.isLoggable(Level.FINEST)) logger.finest(this.getClass().getSimpleName() + "(" + engineid + ")" + " start keeplive(wsmaxconns:" + wsmaxconns + ", delay:" + delay + "s, interval:" + liveinterval + "s) scheduler executor");
} }
void destroy(AnyValue conf) { void destroy(AnyValue conf) {

View File

@@ -137,6 +137,7 @@ class WebSocketRunner implements Runnable {
failed(null, attachment1); failed(null, attachment1);
return; return;
} }
if (packet.type == FrameType.TEXT) { if (packet.type == FrameType.TEXT) {
try { try {
if (packet.receiveType == WebSocketPacket.MessageType.STRING) { if (packet.receiveType == WebSocketPacket.MessageType.STRING) {
@@ -148,7 +149,7 @@ class WebSocketRunner implements Runnable {
webSocket.onMessage(packet.receiveMessage, packet.last); webSocket.onMessage(packet.receiveMessage, packet.last);
} }
} }
} catch (Exception e) { } catch (Throwable e) {
context.getLogger().log(Level.SEVERE, "WebSocket onTextMessage error (" + packet + ")", e); context.getLogger().log(Level.SEVERE, "WebSocket onTextMessage error (" + packet + ")", e);
} }
} else if (packet.type == FrameType.BINARY) { } else if (packet.type == FrameType.BINARY) {
@@ -162,7 +163,7 @@ class WebSocketRunner implements Runnable {
webSocket.onMessage(packet.receiveMessage, packet.last); webSocket.onMessage(packet.receiveMessage, packet.last);
} }
} }
} catch (Exception e) { } catch (Throwable e) {
context.getLogger().log(Level.SEVERE, "WebSocket onBinaryMessage error (" + packet + ")", e); context.getLogger().log(Level.SEVERE, "WebSocket onBinaryMessage error (" + packet + ")", e);
} }
} else if (packet.type == FrameType.PING) { } else if (packet.type == FrameType.PING) {
@@ -173,13 +174,13 @@ class WebSocketRunner implements Runnable {
} }
} else if (packet.type == FrameType.PONG) { } else if (packet.type == FrameType.PONG) {
try { try {
if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner onMessage by PONG FrameType : " + packet);
webSocket.onPong((byte[]) packet.receiveMessage); webSocket.onPong((byte[]) packet.receiveMessage);
} catch (Exception e) { } catch (Exception e) {
context.getLogger().log(Level.SEVERE, "WebSocket onPong error (" + packet + ")", e); context.getLogger().log(Level.SEVERE, "WebSocket onPong error (" + packet + ")", e);
} }
} else if (packet.type == FrameType.CLOSE) { } else if (packet.type == FrameType.CLOSE) {
Logger logger = context.getLogger(); if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner onMessage by CLOSE FrameType : " + packet);
if (debug) logger.log(Level.FINEST, "WebSocketRunner onMessage by CLOSE FrameType : " + packet);
closeRunner(0, "received CLOSE frame-type message"); closeRunner(0, "received CLOSE frame-type message");
return; return;
} else { } else {
@@ -204,7 +205,7 @@ class WebSocketRunner implements Runnable {
if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner abort by AsyncConnection closed"); if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner abort by AsyncConnection closed");
closeRunner(RETCODE_WSOCKET_CLOSED, "webSocket channel is not opened"); closeRunner(RETCODE_WSOCKET_CLOSED, "webSocket channel is not opened");
} }
} catch (Exception e) { } catch (Throwable e) {
if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner abort on read bytes from channel, force to close channel, live " + (System.currentTimeMillis() - webSocket.getCreatetime()) / 1000 + " seconds", e); if (debug) context.getLogger().log(Level.FINEST, "WebSocketRunner abort on read bytes from channel, force to close channel, live " + (System.currentTimeMillis() - webSocket.getCreatetime()) / 1000 + " seconds", e);
closeRunner(0, "read bytes from channel error"); closeRunner(0, "read bytes from channel error");
} }

View File

@@ -11,7 +11,7 @@ import java.nio.charset.Charset;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.redkale.net.*; import org.redkale.net.*;
import org.redkale.util.ObjectPool; import org.redkale.util.*;
/** /**
* <p> * <p>
@@ -22,9 +22,9 @@ import org.redkale.util.ObjectPool;
public class SncpContext extends Context { public class SncpContext extends Context {
public SncpContext(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool, public SncpContext(long serverStartTime, Logger logger, ThreadPoolExecutor executor, int bufferCapacity, ObjectPool<ByteBuffer> bufferPool,
ObjectPool<Response> responsePool, int maxbody, Charset charset, InetSocketAddress address, PrepareServlet prepare, ObjectPool<Response> responsePool, int maxbody, Charset charset, InetSocketAddress address, ResourceFactory resourceFactory, PrepareServlet prepare,
int readTimeoutSecond, int writeTimeoutSecond) { int readTimeoutSecond, int writeTimeoutSecond) {
super(serverStartTime, logger, executor, bufferCapacity, bufferPool, responsePool, maxbody, charset, super(serverStartTime, logger, executor, bufferCapacity, bufferPool, responsePool, maxbody, charset,
address, prepare, readTimeoutSecond, writeTimeoutSecond); address, resourceFactory, prepare, readTimeoutSecond, writeTimeoutSecond);
} }
} }

View File

@@ -25,11 +25,15 @@ import org.redkale.util.*;
public class SncpServer extends Server<DLong, SncpContext, SncpRequest, SncpResponse, SncpServlet> { public class SncpServer extends Server<DLong, SncpContext, SncpRequest, SncpResponse, SncpServlet> {
public SncpServer() { public SncpServer() {
this(System.currentTimeMillis()); this(System.currentTimeMillis(), ResourceFactory.root());
} }
public SncpServer(long serverStartTime) { public SncpServer(ResourceFactory resourceFactory) {
super(serverStartTime, "TCP", new SncpPrepareServlet()); this(System.currentTimeMillis(), resourceFactory);
}
public SncpServer(long serverStartTime, ResourceFactory resourceFactory) {
super(serverStartTime, "TCP", resourceFactory, new SncpPrepareServlet());
} }
@Override @Override
@@ -103,7 +107,7 @@ public class SncpServer extends Server<DLong, SncpContext, SncpRequest, SncpResp
AtomicLong cycleResponseCounter = new AtomicLong(); AtomicLong cycleResponseCounter = new AtomicLong();
ObjectPool<Response> responsePool = SncpResponse.createPool(createResponseCounter, cycleResponseCounter, this.responsePoolSize, null); ObjectPool<Response> responsePool = SncpResponse.createPool(createResponseCounter, cycleResponseCounter, this.responsePoolSize, null);
SncpContext sncpcontext = new SncpContext(this.serverStartTime, this.logger, executor, rcapacity, bufferPool, responsePool, SncpContext sncpcontext = new SncpContext(this.serverStartTime, this.logger, executor, rcapacity, bufferPool, responsePool,
this.maxbody, this.charset, this.address, this.prepare, this.readTimeoutSecond, this.writeTimeoutSecond); this.maxbody, this.charset, this.address, this.resourceFactory, this.prepare, this.readTimeoutSecond, this.writeTimeoutSecond);
responsePool.setCreator((Object... params) -> new SncpResponse(sncpcontext, new SncpRequest(sncpcontext))); responsePool.setCreator((Object... params) -> new SncpResponse(sncpcontext, new SncpRequest(sncpcontext)));
return sncpcontext; return sncpcontext;
} }