【怎么做到随机选择服务器? _分布式 】 | IT修真院·坑乎
问题已收录 怎么做到随机选择服务器?
我也踩过这个坑( 1 )
已统计您的踩坑,无需重复点击
回答(2)
分布式
详细描述
错误截图
源码
编辑于2024-11-18
  • [无名弟子]李恪非
    0

    可以通过以下代码的思路做,或者自己写一个轮询工厂:

       @Scheduled(cron = "0 0/3 * * * ?")
    private static void print(){
    flagA=0;
    flagB=0;
    System.out.print("将A、B清0\n");
    }

    //   private static ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //   private static UserRmiService userRmiService = (UserRmiService) context.getBean("loadBalancedService");


      private static UserRmiService load(){
    if (Math.random()<0.5 && flagA==0) {
    try {
    System.out.print("准备调用:");
    userRmiService = (UserRmiService) context.getBean("userRmiServiceA");
    System.out.print("调用成功8080端口"+userRmiService+"\n");
    }
    catch (Exception e ){
    flagA = 1;
    userRmiService = (UserRmiService) context.getBean("userRmiServiceB");
    System.out.print("调用失败尝试调用:"+userRmiService+"\n");
    }
    }
    else  if (flagB==0){
    try {
    System.out.print("准备调用:");
    userRmiService = (UserRmiService) context.getBean("userRmiServiceB");
    System.out.print("调用成功8082端口"+userRmiService+"\n");
    }
    catch (Exception e){
    flagB = 1;
    userRmiService = (UserRmiService) context.getBean("userRmiServiceA");
    System.out.print("调用失败尝试调用:"+userRmiService+"\n");
    }
    }
    else if(flagA==1 && flagB ==1) {
    System.out.print("两个端口都挂了,你在搞毛线\n");
    }
    return userRmiService;
    }


    编辑于2018-05-19
  • [西安|荣耀师兄]JAVA-孙若飞
    0

    使用随机数和try catch

    编辑于2019-05-14