主程序代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | /* /* * CopyRight (c) 2013 北京软秀科技有限公司www.inforwms.com 保留所有权利。<br> * mail:meslog@qq.com */ */ package com.softshow.product.digi; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.text.DateFormat; import java.text.FieldPosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.InvalidPropertiesFormatException; import java.util.LinkedList; import java.util.List; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.ConsoleHandler; import java.util.logging.FileHandler; import java.util.logging.Formatter; import java.util.logging.LogRecord; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.util.internal.ConcurrentHashMap; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import com.softshow.product.cache.DataCache; import com.softshow.product.db.DatabaseDataManager; import com.softshow.product.handler.IdentifyChannelDecoder; import com.softshow.product.handler.InitInfoChannelDecoder; import com.softshow.product.helper.DateUtils; import com.softshow.product.helper.GlobalTimer; import com.softshow.product.helper.HttpClientHelper; import com.softshow.product.helper.Log; import com.softshow.product.model.CarInfo; import com.softshow.product.timer.AutoUpgradTimer; import com.softshow.product.timer.AutoOrderTimer; import com.softshow.product.timer.WSAutoOrderTimer; /** * 服务统一管理 * @author <a href="mailto:meslog@qq.com">meslog</a> * @version 1.0.0.2013-10-22 * */ public class ServerManager { private final String cfgPath = "/server.cfg" ; private final List<TrackerServer> serverList = new LinkedList<TrackerServer>(); private final static ConcurrentMap<Integer,TrackerServer> trackerServerMap = new ConcurrentHashMap<Integer,TrackerServer>(); //lizhao public static ConcurrentMap<Integer,TrackerServer> getTrackerServerMap(){ //lizhao return trackerServerMap; } public void addTrackerServer(TrackerServer trackerServer) { serverList.add(trackerServer); } private boolean loggerEnabled; public boolean isLoggerEnabled() { return loggerEnabled; } private static DataManager dataManager; public static DataManager getDataManager() { return dataManager; } private static Properties properties; public Properties getProperties() { return properties; } private static JedisConnectionFactory redisFactory; public static JedisConnectionFactory getRedisFactory() { return redisFactory; } /** * 初始化日志、缓存、数据库和Netty服务 */ public void init() throws IOException, ClassNotFoundException, SQLException { loadProperties(); //加载配置,初始化常量 initLogger(properties); //初始化日志 dataManager = new DatabaseDataManager(properties); //初始化数据库连接 Log.info(Constants.SERVER_MAIN, "**database connection initialized......**" ); redisFactory = initRedis(properties); //初始化redis缓存 initDataCache(); //加载redis缓存 Log.info(Constants.SERVER_MAIN, "**redis load compeleted......**" ); initELSServer( "fourfaith" ); //初始化Netty服务 } private void loadProperties() throws InvalidPropertiesFormatException, IOException{ //加载配置文件 properties = new Properties(); InputStream in = getClass().getResourceAsStream(cfgPath); properties.loadFromXML(in); in.close(); //打印版本信息 Constants.VERSION_CODE = properties.getProperty( "connection.version" ); Log.info(Constants.SERVER_MAIN, "===============================system version:[" +Constants.VERSION_CODE+ "]" ); //初始化常量 initConstant(properties); } /** * 每天定时清理缓存数据 */ private void scheduleDailyGpsCache() { final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisFactory); redisTemplate.setKeySerializer( new StringRedisSerializer()); redisTemplate.afterPropertiesSet(); Timer timer = new java.util.Timer( true ); final List<CarInfo> carList = DataCache.getAllCar(); TimerTask task = new TimerTask() { public void run() { for (CarInfo car : carList) { redisTemplate.delete(Constants.CACHE.TODAY_GPS_COLLECTION_PREFIX + "." + car.getId()); } } }; timer.scheduleAtFixedRate(task, DateUtils.getTomorrowTimeByHour( 0 ), 24 * 60 * 60 * 1000 ); } private JedisConnectionFactory initRedis(Properties prop) { redisFactory = new JedisConnectionFactory(); redisFactory.setUsePool( true ); redisFactory.setPort(Integer.parseInt(prop.getProperty( "redis.port" ))); redisFactory.setHostName(prop.getProperty( "redis.serverUrl" )); redisFactory.setDatabase(Integer.parseInt(prop.getProperty( "redis.database" ))); redisFactory.afterPropertiesSet(); return redisFactory; } /** * 启动Netty服务和相关定时线程 */ public void start() { //启动Netty Server for (Object server : serverList) { ((TrackerServer) server).start(); } //启动定时器 startTimer(); } /** * Stop */ public void stop() { for (Object server : serverList) { ((TrackerServer) server).stop(); } // Release resources GlobalChannelFactory.release(); GlobalTimer.release(); try { redisFactory.destroy(); } catch (Exception e) { e.printStackTrace(); } } /** * Destroy */ public void destroy() { serverList.clear(); } /** * Initialize logger */ private void initLogger(Properties properties) throws IOException { loggerEnabled = Boolean.valueOf(properties.getProperty( "logger.enable" )); if (loggerEnabled) { String serverMainName = properties.getProperty( "logger.servermain" ); initLog(serverMainName,Constants.SERVER_MAIN); String serverGpsName = properties.getProperty( "logger.servergps" ); initLog(serverGpsName,Constants.GPS_LOGGER_SERVER); String serverHeartName = properties.getProperty( "logger.serverheart" ); initLog(serverHeartName,Constants.HEART_LOGGER_SERVER); } } /** * 初始化常量 * @param properties * @throws IOException */ private void initConstant(Properties props) throws IOException { String webPrefix = "http://" + props.getProperty( "webIP" ); String ctx = props.getProperty( "webContext" ); if (ctx!= null && ctx.trim().length()> 0 ){ webPrefix += "/" +ctx; } Constants.query_Order_url = webPrefix + Constants.query_Order_url; Constants.setRange_url = webPrefix + Constants.setRange_url; Constants.getDeviceParameter_url = webPrefix + Constants.getDeviceParameter_url; HttpClientHelper.MapbarAPIAddr = props.getProperty( "mapBarAPIAddress" ); } private boolean isProtocolEnabled(Properties properties, String protocol) { String enabled = properties.getProperty(protocol + ".enable" ); if (enabled != null ) { return Boolean.valueOf(enabled); } return false ; } private void initServer(String protocol) throws SQLException { //lizhao if (isProtocolEnabled(properties, protocol)) { TrackerServer trackerServer = new TrackerServer( this , new ServerBootstrap(), protocol) { @Override protected void addSpecificHandlers(ChannelPipeline pipeline) { //进行了编码和解码.之前的handler处理字节,之后的handler处理字符串。顺序不可乱。 pipeline.addLast( "stringDecoder" , new StringDecoder()); pipeline.addLast( "stringEncoder" , new StringEncoder()); pipeline.addLast( "identifyDeviceDecoder" , new IdentifyChannelDecoder(ServerManager. this )); pipeline.addLast( "initInfoChannelDecoder" , new InitInfoChannelDecoder(ServerManager. this )); } }; trackerServerMap.put(trackerServer.getPort(), trackerServer); serverList.add(trackerServer); } } /** * * Description:启动时初始化数据缓存 */ private void initDataCache() { new DataCache(dataManager); } /** * 初始化日志 * @param name * @param sgin * @throws IOException */ private void initLog(String name,String sgin) throws IOException{ if (name != null ) { FileHandler file = new FileHandler(name, 500 * 1024 * 1024 , 10 , true ); // Simple formatter file.setFormatter( new Formatter() { private final String LINE_SEPARATOR = System.getProperty( "line.separator" , "\n" ); private final DateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); @Override public String format(LogRecord record) { StringBuffer line = new StringBuffer(); dateFormat.format( new Date(record.getMillis()), line, new FieldPosition( 0 )); line.append( " " ); line.append(record.getSourceClassName()); line.append( "." ); line.append(record.getSourceMethodName()); line.append( " " ); line.append(record.getLevel().getName()); line.append( ": " ); line.append(formatMessage(record)); line.append(LINE_SEPARATOR); return line.toString(); } }); Log.getLogger(sgin).addHandler(file); //文件输出 Log.getLogger(sgin).addHandler( new ConsoleHandler()); //控制台输出 } } /** * 启动定时任务 * @param dataManager */ public void startTimer(){ // webservice定时获取订单 ScheduledExecutorService executorWSOrder = Executors.newScheduledThreadPool( 1 ); executorWSOrder.scheduleWithFixedDelay( new WSAutoRecieveOrderTimer(dataManager), 10 , 300 , TimeUnit.SECONDS); Log.info(Constants.SERVER_MAIN, "**Timer[receive order] running per 300s......**" ); // 定时订单 ScheduledExecutorService deliverOrder = Executors.newScheduledThreadPool( 2 ); deliverOrder.scheduleWithFixedDelay( new AutoSendOrderTimer(dataManager), 10 , 180 , TimeUnit.SECONDS); Log.info(Constants.SERVER_MAIN, "**Timer[auto send order] running per 180s......**" ); // GPS缓存定时清理 scheduleDailyGpsCache(); Log.info(Constants.SERVER_MAIN, "**Timer[GPS data cleaner] running per day......**" ); // 定时检查升级是否超时 ScheduledExecutorService deviceUpgrade = Executors.newScheduledThreadPool( 3 ); deviceUpgrade.scheduleWithFixedDelay( new AutoCheckUpgradTimer(dataManager), 20 , 60 , TimeUnit.SECONDS); Log.info(Constants.SERVER_MAIN, "**Timer[auto check upgrade device] running per 60s......**" ); } } |