记一次自定义管理工厂使用spring自动装载bean

1.核心工厂配置类

@Component
public class HandlerContext {

private Map<String, AbstractHandler> handlerMap;

private HandlerContext() {
}

private void init(Map<String, AbstractHandler> handlerMap) {
this.handlerMap = handlerMap;
}

public AbstractHandler getInstance(String type) {
AbstractHandler handler = handlerMap.get(type);
if (handler == null) {
System.out.println("没有type为‘" + type + "’的处理器");
throw new IllegalArgumentException("not found handler for type: " + type);
}
return handler;
}

//初始化处理器
@Bean
private Map<String, AbstractHandler> initHandlerContext(Map<String, AbstractHandler> handlerMap){
this.init(handlerMap);
return this.handlerMap;
}

}

2.抽象处理父类
public abstract class AbstractHandler {

protected static final Logger log = LoggerFactory.getLogger(AbstractHandler.class);

@Autowired
protected HandlerThreadPool handlerThreadPool;
@Autowired
protected RedisTemplate redisTemplate;

public abstract String handler(ChannelHandlerContext ctx, NettyMessage message);

}

3.子类写法 需使用spring的service注解
@Service("base")
public class BaseHandler extends AbstractHandler

@Service("mls")
public class GameMLSHandler extends AbstractHandler

等等等·····

4. 使用
AbstractHandler handler = handlerContext.getInstance(message.getType());
handler.handler(ctx, message);

5.线程池数组
可根据角标指定哪一个线程去处理,可解决部分多次发送等多线程问题。
@Component
public class HandlerThreadPool {

//线程池数组
private static ExecutorService[] handlerThreadPool = new ExecutorService[5];

public HandlerThreadPool() {
for (int i = 0; i < handlerThreadPool.length; i++) {
handlerThreadPool[i] = Executors.newFixedThreadPool(1);
}
}

public ExecutorService getHandlerThread(int index){
return index > handlerThreadPool.length ? null : handlerThreadPool[index];
}

public static int getThreadSize(){
return handlerThreadPool.length;
}
}
以上的NettyMessage为自定义消息类,需根据具体业务自行编写


原文地址:https://www.cnblogs.com/bzdofj/p/14209410.html