构建GrizzlyHttpServer

<!-- lang: java -->

==>ServiceServer

public interface ServiceServer {

    public void start();

}

==>ServerConfig

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

public class ServerConfig {
	
	public final static String LISTENER_IP = "listenerIp";
    public final static String LISTENER_PORT = "listenerPort";
	public final static String LISTENER_NAME = "listenerName";
	public final static String THREAD_POOL_NAME = "threadPoolName";
	public final static String CORE_THREAD_POOL_SIZE = "coreThreadPoolSize";
	public final static String MAX_THREAD_POOL_SIZE = "maxThreadPoolSize";
	public final static String QUEUE_LIMIT = "queueLimit";
	public final static String SELECTOR_RUNNERS = "selectorRunners";
	public final static String STANDALONE = "standalone";

    public final static String TRANSACTION_TIMEOUT = "transactionTimeout";
	
	public final static String API_LIST = "apiList";
	
	public final static String REST_BASE_URI = "restBaseUri";
	public final static String REST_RESOURCE_PATH = "restResourcePath";
	
	public final static String IO_STRATEGY = "IOStrategy";
	
	public final static String KEEP_ALIVE = "keepAlive";
	public final static String TCP_NO_DELAY = "tcpNoDelay";
	
	public final static String COMPRESSION_MODE = "compressionMode";
	public final static String COMPRESSION_MIN_SIZE = "compressionMinSize";
	public final static String COMPRESSABLE_MINE_TYPES = "compressableMimeTypes";
	
	public final static String IS_ACCESS_LOG = "isAccessLog";
	public final static String ACCESS_LOG_PATH = "accessLogPath";
	
	public final static String INDEX_PATH = "indexPath";
	public final static String DATA_PATH = "dataPath";
	
	public static final String SERVER_RESOURCE_NAME = "server-info";
	
	public static final String SERVER_NAME = "serverName";
	public static final String SERVER_VERSION = "serverVersion";

	private static ResourceBundle serverResourceBundle;

	static {
		serverResourceBundle = ResourceBundle.getBundle(SERVER_RESOURCE_NAME);
	}

	public static String getValue(String key) {
		return serverResourceBundle.getString(key);
	}
	
	public static String getListenerIp() {
		String listenerIp = getValue(ServerConfig.LISTENER_IP);
		if (listenerIp != null && listenerIp.length() > 0 && listenerIp.split(".").length == 4) {
			return listenerIp;
		} else {
			return "0.0.0.0";
		}
	}
	
	public static int getListenerPort() {
		String listenerPort = getValue(ServerConfig.LISTENER_PORT);
		int port = 8090;
		if (listenerPort != null && listenerPort.length() > 0 ) {
			try {
				port = Integer.parseInt(listenerPort);
				if(port <= 1024) {
					port = 8090;
				}
			} catch (NumberFormatException nfe) {
				port = 8090;
			}
		} 
		return port;
	}
	
	public static int getCompressionMinSize() {
		String compressionMinSize = getValue(ServerConfig.COMPRESSION_MIN_SIZE);
		int size = 1;
		if (compressionMinSize != null && compressionMinSize.length() > 0 ) {
			try {
				size = Integer.parseInt(compressionMinSize);
			} catch (NumberFormatException nfe) {
				size = 1;
			}
		} 
		return size;
	}
	
	public static String getListenerName() {
		String listenerName = getValue(ServerConfig.LISTENER_NAME);
		if (listenerName != null && listenerName.length() > 0 ) {
			return listenerName;
		} else {
			return "Juaby-Listener";
		}
	}
	
	public static String getThreadPoolName() {
		String threadPoolName = getValue(ServerConfig.THREAD_POOL_NAME);
		if (threadPoolName != null && threadPoolName.length() > 0 ) {
			return threadPoolName;
		} else {
			return "Juaby-Pool";
		}
	}
	
	public static String getServerName() {
		String serverName = getValue(ServerConfig.SERVER_NAME);
		if (serverName != null && serverName.length() > 0 ) {
			return serverName;
		} else {
			return "JusbyHttpServer";
		}
	}
	
	public static String getRestBaseUri() {
		String restBaseUri = getValue(ServerConfig.REST_BASE_URI);
		if (restBaseUri != null && restBaseUri.length() > 0 ) {
			return restBaseUri;
		} else {
			return "/api";
		}
	}
	
	public static String getRestResourcePath() {
		String restResourcePath = getValue(ServerConfig.REST_RESOURCE_PATH);
		if (restResourcePath != null && restResourcePath.length() > 0 ) {
			return restResourcePath;
		} else {
			return "com.mapbar";
		}
	}
	
	public static String getServerVersion() {
		String serverVersion = getValue(ServerConfig.SERVER_VERSION);
		if (serverVersion != null && serverVersion.length() > 0 ) {
			return serverVersion;
		} else {
			return "0.0.9";
		}
	}
	
	public static String getCompressionMode() {
		String compressionMode = getValue(ServerConfig.COMPRESSION_MODE);
		if (compressionMode != null && compressionMode.length() > 0 ) {
			return compressionMode;
		} else {
			return "ON";
		}
	}
	
	public static String getCompressableMimeTypes() {
		String compressableMimeTypes = getValue(ServerConfig.COMPRESSABLE_MINE_TYPES);
		if (compressableMimeTypes != null && compressableMimeTypes.length() > 0 ) {
			return compressableMimeTypes;
		} else {
			return "text/plain," + "text/html," + "binary/octet-stream";
		}
	}

	public static boolean getStandalone() {
		String standalone = getValue(ServerConfig.STANDALONE);
		if (standalone != null && standalone.length() > 0 ) {
			return Boolean.parseBoolean(standalone);
		} else {
			return false;
		}
	}
	
	public static boolean getKeepAlive() {
		String keepAlive = getValue(ServerConfig.KEEP_ALIVE);
		if (keepAlive != null && keepAlive.length() > 0 ) {
			return Boolean.parseBoolean(keepAlive);
		} else {
			return false;
		}
	}
	
	public static boolean getTcpNoDelay() {
		String tcpNoDelay = getValue(ServerConfig.TCP_NO_DELAY);
		if (tcpNoDelay != null && tcpNoDelay.length() > 0 ) {
			return Boolean.parseBoolean(tcpNoDelay);
		} else {
			return false;
		}
	}
	
	public static boolean getIsAccessLog() {
		String isAccessLog = getValue(ServerConfig.IS_ACCESS_LOG);
		if (isAccessLog != null && isAccessLog.length() > 0 ) {
			return Boolean.parseBoolean(isAccessLog);
		} else {
			return false;
		}
	}
	
	public static String getAccessLogPath() {
		String accessLogPath = getValue(ServerConfig.ACCESS_LOG_PATH);
		if (accessLogPath != null && accessLogPath.length() > 0 ) {
			return accessLogPath;
		} else {
			return "/tmp/access.log";
		}
	}
	
	public static String getIndexPath() {
		String indexPath = getValue(ServerConfig.INDEX_PATH);
		if (indexPath != null && indexPath.length() > 0 ) {
			return indexPath;
		} else {
			return "/index";
		}
	}
	
	public static String getDataPath() {
		String dataPath = getValue(ServerConfig.DATA_PATH);
		if (dataPath != null && dataPath.length() > 0 ) {
			return dataPath;
		} else {
			return "/data";
		}
	}
	
	public static int getCoreThreadPoolSize() {
		String coreThreadPoolSize = getValue(ServerConfig.CORE_THREAD_POOL_SIZE);
		int coreSize = Runtime.getRuntime().availableProcessors() * 2;
		if (coreThreadPoolSize != null && coreThreadPoolSize.length() > 0 ) {
			try {
				coreSize = Integer.parseInt(coreThreadPoolSize);
				if(coreSize <= 0) {
					coreSize = Runtime.getRuntime().availableProcessors() * 2;
				}
			} catch (NumberFormatException nfe) {
				coreSize = Runtime.getRuntime().availableProcessors() * 2;
			}
		} 
		return coreSize;
	}
	
	public static int getMaxThreadPoolSize() {
		String maxThreadPoolSize = getValue(ServerConfig.MAX_THREAD_POOL_SIZE);
		int maxSize = Runtime.getRuntime().availableProcessors() * 2;
		if (maxThreadPoolSize != null && maxThreadPoolSize.length() > 0 ) {
			try {
				maxSize = Integer.parseInt(maxThreadPoolSize);
				if(maxSize <= 0) {
					maxSize = Runtime.getRuntime().availableProcessors() * 2;
				}
			} catch (NumberFormatException nfe) {
				maxSize = Runtime.getRuntime().availableProcessors() * 2;
			}
		} 
		return maxSize;
	}
	
	public static int getQueueLimit() {
		String queueLimit = getValue(ServerConfig.QUEUE_LIMIT);
		int queueLimitSize = 1000;
		if (queueLimit != null && queueLimit.length() > 0 ) {
			try {
				queueLimitSize = Integer.parseInt(queueLimit);
				if(queueLimitSize <= 0) {
					queueLimitSize = 1000;
				}
			} catch (NumberFormatException nfe) {
				queueLimitSize = 1000;
			}
		} 
		return queueLimitSize;
	}
	
	public static int getSelectorRunners() {
		String selectorRunners = getValue(ServerConfig.SELECTOR_RUNNERS);
		int selectorRunnersSize = Runtime.getRuntime().availableProcessors();
		if (selectorRunners != null && selectorRunners.length() > 0 ) {
			try {
				selectorRunnersSize = Integer.parseInt(selectorRunners);
				if(selectorRunnersSize <= 0) {
					selectorRunnersSize = Runtime.getRuntime().availableProcessors();
				}
			} catch (NumberFormatException nfe) {
				selectorRunnersSize = Runtime.getRuntime().availableProcessors();
			}
		} 
		return selectorRunnersSize;
	}
	
	public static int getTransactionTimeout() {
		String transactionTimeout = getValue(ServerConfig.TRANSACTION_TIMEOUT);
		int transactionTimeoutSize = Runtime.getRuntime().availableProcessors();
		if (transactionTimeout != null && transactionTimeout.length() > 0 ) {
			try {
				transactionTimeoutSize = Integer.parseInt(transactionTimeout);
				if(transactionTimeoutSize <= 0) {
					transactionTimeoutSize = 10;
				}
			} catch (NumberFormatException nfe) {
				transactionTimeoutSize = 10;
			}
		} 
		return transactionTimeoutSize;
	}
	
	public static Map<String, Object> getApiList() {
		String apiList = getValue(ServerConfig.API_LIST);
		Map <String, Object> apiMap = new HashMap<String, Object>();
		if (apiList != null && apiList.length() > 0 ) {
			String [] apiArray = apiList.split(";");
			for (int i = 0; i < apiArray.length; i++) {
				String [] api = apiArray[i].split(":");
				try {
					apiMap.put(api[1], Class.forName(api[0]).newInstance());
				} catch (InstantiationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return apiMap;
		} else {
			return apiMap;
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static Object getIOStrategy() {
		String ioStrategy = getValue(ServerConfig.IO_STRATEGY);
		Object strategy = null;
		try {
			Constructor constructor = Class.forName(ioStrategy).getDeclaredConstructor();   
			constructor.setAccessible(true);   
			strategy = constructor.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strategy;
	}

}

==>GrizzlyHttpServer

import java.io.IOException;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.ext.RuntimeDelegate;

import org.glassfish.grizzly.IOStrategy;
import org.glassfish.grizzly.http.CompressionConfig;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.http.server.accesslog.AccessLogBuilder;
import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
import org.glassfish.grizzly.utils.DelayedExecutor;
import org.glassfish.grizzly.utils.IdleTimeoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xxx.wirelessrd.server.search.init.SystemInitUtil;

public class GrizzlyHttpServer implements ServiceServer {

        static Logger logger = LoggerFactory.getLogger(GrizzlyHttpServer.class.getName());
    	
    	public static HttpServer getGrizzlyHttpServer() {
    		HttpServer httpServer = new HttpServer();
    		NetworkListener networkListener = new NetworkListener(ServerConfig.getListenerName(), ServerConfig.getListenerIp(), ServerConfig.getListenerPort());
    		final DelayedExecutor timeoutExecutor = IdleTimeoutFilter.createDefaultIdleDelayedExecutor();
    		timeoutExecutor.start();
    		
    		//设置工作线程池
    		ThreadPoolConfig threadPoolConfig = ThreadPoolConfig.defaultConfig()
    				.setCorePoolSize(ServerConfig.getCoreThreadPoolSize())
    				.setMaxPoolSize(ServerConfig.getMaxThreadPoolSize())
    				// .setQueue(null)
    				.setQueueLimit(ServerConfig.getQueueLimit())
    				// .setThreadFactory(null)
    				.setPoolName(ServerConfig.getThreadPoolName())
    				// .setPriority(5)
    				// .setKeepAliveTime(10, TimeUnit.SECONDS)
    				.setTransactionTimeout(timeoutExecutor, ServerConfig.getTransactionTimeout(), TimeUnit.SECONDS);
    		networkListener.getTransport().setWorkerThreadPoolConfig(threadPoolConfig);
    		
    		//networkListener.getTransport().setMemoryManager(ByteBufferManager.DEFAULT_MEMORY_MANAGER);
    		
    		networkListener.getTransport().setSelectorRunnersCount(ServerConfig.getSelectorRunners());
    		
    		networkListener.getTransport().configureStandalone(ServerConfig.getStandalone());
    		
    		IOStrategy ioStrategy = (IOStrategy)ServerConfig.getIOStrategy();
    		if (ioStrategy != null) {
    			networkListener.getTransport().setIOStrategy(ioStrategy);
    		}
    		
    		//开启长连接
    		networkListener.getTransport().setKeepAlive(ServerConfig.getKeepAlive());
    		//关闭Nagle算法
    		networkListener.getTransport().setTcpNoDelay(ServerConfig.getTcpNoDelay());
    		
    		//关闭默认错误页面
    		networkListener.setDefaultErrorPageGenerator(null);
    		
    		//开启压缩
    		CompressionConfig compressionConfig = networkListener.getCompressionConfig();
    		compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.fromString(ServerConfig.getCompressionMode())); // the mode
    		compressionConfig.setCompressionMinSize(ServerConfig.getCompressionMinSize()); // the min amount of bytes to compress
    		compressionConfig.setCompressableMimeTypes(ServerConfig.getCompressableMimeTypes()); // the mime types to compress
    		
    		httpServer.addListener(networkListener);
    		
    		//关闭默认错误页面
    		httpServer.getServerConfiguration().setDefaultErrorPageGenerator(null);
    		
    		//是否开启接入日志
    		boolean isAccessLog = ServerConfig.getIsAccessLog();
    		if (isAccessLog) {
    			final AccessLogBuilder builder = new AccessLogBuilder(ServerConfig.getAccessLogPath());
    			//builder.format("%q");
    			//builder.timeZone("Asia/Shanghai");
    			builder.rotatedDaily();
    			builder.statusThreshold(200);
    			builder.instrument(httpServer.getServerConfiguration());
    		}
    		
    		//添加业务逻辑
    		for (Entry<String, Object> m : ServerConfig.getApiList().entrySet()) {
    			httpServer.getServerConfiguration().addHttpHandler((HttpHandler)m.getValue(), new String[] { m.getKey() });
    		}
    		
    		//支持Jersey REST
    		HttpHandler endpoint = RuntimeDelegate.getInstance().createEndpoint(new JuabyApplication(ServerConfig.getRestResourcePath()), HttpHandler.class);
    		httpServer.getServerConfiguration().addHttpHandler(endpoint, new String[] { ServerConfig.getRestBaseUri() });
    		
    		httpServer.getServerConfiguration().setHttpServerName(ServerConfig.getServerName());
    		httpServer.getServerConfiguration().setHttpServerVersion(ServerConfig.getServerVersion());
    		return httpServer;
    	}
    
    	public void start() {
    			try {
    				logger.info("-----------------------------服务启动开始-----------------------------");
    				HttpServer httpServer = getGrizzlyHttpServer();
    				httpServer.start();
    				SystemInitUtil.init();
    				logger.info("-----------------------------服务启动结束-----------------------------");
    				Thread.currentThread().join();
    			} catch (IOException e) {
    				logger.info("-----------------------------服务启动失败-----------------------------", e);
    			} catch (InterruptedException e) {
    				logger.info("-----------------------------服务启动失败-----------------------------", e);
    			}
    	}

}

==>server-info.properties

#监听IP
listenerIp = 0.0.0.0
#监听PORT
listenerPort = 8099
#监听PORT
listenerName = Juaby-Listener
#线程池名
threadPoolName = Juaby-Pool
#线程池初始值
coreThreadPoolSize = 12
#线程池最大值
maxThreadPoolSize = 12
#线程池队列大小
queueLimit = -1
#线程处理超时时间
transactionTimeout = 10

#选择器大小
selectorRunners = 16

standalone = false

#IOStrategy = org.glassfish.grizzly.strategies.SameThreadIOStrategy
IOStrategy = org.glassfish.grizzly.strategies.WorkerThreadIOStrategy
#IOStrategy = org.glassfish.grizzly.strategies.LeaderFollowerNIOStrategy
#IOStrategy = org.glassfish.grizzly.strategies.SimpleDynamicNIOStrategy

keepAlive = true
tcpNoDelay = true

compressionMode = ON
compressionMinSize = 1
compressableMimeTypes = "text/plain", "text/html", "binary/octet-stream"

#接口
apiList = com.xxx.wirelessrd.server.search.service.AlongRoadSearchHandler:/alongroad;\
			  com.xxx.wirelessrd.server.search.service.KeywordSearchHandler:/keyword;\
			  com.xxx.wirelessrd.server.search.service.NearBySearchHandler:/nearby;

restBaseUri = /api
restResourcePath = com.mapbar.wirelessrd.server.search.resources

#AccessLog	
isAccessLog = false		  
accessLogPath = /tmp/access.log
accessLogFormat = 
accessLogTimeZone = 
accessLogRotatedType = 
accessLogStatusThreshold = 

serverName = JusbyHttpServer
serverVersion = 0.0.9

==>JuabyApplication

import org.glassfish.jersey.server.ResourceConfig;

import com.xxx.wirelessrd.server.search.resources.XXXSearchResource;

public class JuabyApplication extends ResourceConfig {

    public JuabyApplication() {
        packages(
        		XXXSearchResource.class.getPackage().getName()
        		);
    }
    
    public JuabyApplication(String resourcePath) {
        packages(resourcePath);
    }

}

==>KeywordSearchHandler

import java.util.HashMap;
import java.util.Map;

import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xxx.wirelessrd.server.search.utils.HttpHandlerUtil;

public class KeywordSearchHandler extends HttpHandler {

	Logger logger = LoggerFactory.getLogger(KeywordSearchHandler.class);
	
	ISearchService iss = new KeywordSearchService();

	// -------------------------------------------- Methods from HttpHandler
	@SuppressWarnings("all")
	@Override
	public void service(final Request request, final Response response) throws Exception {
		
		// Disable internal Response buffering
		response.setBufferSize(0);

		// get query parametersr
    	Map<String, String[]> param = request.getParameterMap();
    	Map<String, String> otherParam = new HashMap<String, String>();
    	otherParam.put("url", request.getRequestURL() + "?" + request.getQueryString());
    	otherParam.put("userIp", request.getRemoteAddr());
	    
    	final Object object = iss.service(param, otherParam);
    	Object result [] = iss.serializer(object);
		byte [] os = (byte [])result[0];
		final int ossize = (Integer)result[1];
		
		HttpHandlerUtil.write(request, response, os, ossize);
	}

} // END NonBlockingEchoHandler

==>pom.xml

<dependency>
        <groupId>org.glassfish.jersey.core</groupId>
		<artifactId>jersey-common</artifactId>
		<version>2.5.1</version>
	</dependency>
	<dependency>
		<groupId>org.glassfish.jersey.core</groupId>
		<artifactId>jersey-server</artifactId>
		<version>2.5.1</version>
	</dependency>                                       
            <dependency>
		<groupId>org.glassfish.jersey.containers</groupId>
		<artifactId>jersey-container-grizzly2-http</artifactId>
		<version>2.5.1</version>
	</dependency>
            <dependency>
		<groupId>org.glassfish.grizzly</groupId>
		<artifactId>grizzly-http-server</artifactId>
		<version>2.3.11</version>
	</dependency>
            <dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.0.13</version>
	</dependency>
	<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-core</artifactId>
		<version>1.0.13</version>
	</dependency>	
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
		<version>1.7.5</version>
	</dependency>
	<dependency>
		<groupId>com.esotericsoftware.kryo</groupId>
		<artifactId>kryo</artifactId>
		<version>2.22</version>
	</dependency> 

转载于:https://my.oschina.net/sosfate/blog/207470

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值