RpcServer.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package cn.hhj.server;
  2. import cn.hhj.annotation.RpcService;
  3. import cn.hhj.constant.Constant;
  4. import cn.hhj.handler.ProcessorHandler;
  5. import org.springframework.beans.BeansException;
  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.context.ApplicationContext;
  8. import org.springframework.context.ApplicationContextAware;
  9. import org.springframework.util.StringUtils;
  10. import java.net.ServerSocket;
  11. import java.net.Socket;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. import java.util.concurrent.ExecutorService;
  15. import java.util.concurrent.Executors;
  16. public class RpcServer implements ApplicationContextAware, InitializingBean {
  17. ExecutorService service = Executors.newCachedThreadPool();
  18. private Map<String,Object> handlerMap=new HashMap();
  19. @Override
  20. public void afterPropertiesSet() throws Exception {
  21. ServerSocket serverSocket=new ServerSocket(Constant.SERVER_PORT);
  22. while (true){
  23. Socket socket=serverSocket.accept();
  24. service.execute(new ProcessorHandler(socket,handlerMap));
  25. }
  26. }
  27. @Override
  28. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  29. Map<String,Object> serviceBeanMap=applicationContext.getBeansWithAnnotation(RpcService.class);
  30. if (!serviceBeanMap.isEmpty()){
  31. for(Object serviceBean:serviceBeanMap.values()){
  32. RpcService rpcService=serviceBean.getClass().getAnnotation(RpcService.class);
  33. String serviceName=rpcService.value().getName();//拿到接口类定义
  34. String version=rpcService.version(); //拿到版本号
  35. if (!StringUtils.isEmpty(version)){
  36. serviceName+="-"+version;
  37. }
  38. handlerMap.put(serviceName,serviceBean);
  39. }
  40. }
  41. }
  42. }