算法篇
轮训算法
package com. ubiai. wechart. hyundai. manage. action ;
import java. util. ArrayList ;
import java. util. HashMap ;
import java. util. Map ;
import java. util. Set ;
import java. util. concurrent. ConcurrentHashMap ;
public class TestRoundRobin {
public static Map < String , Integer > ipMap= new HashMap < > ( ) ;
static {
ipMap. put ( "192.168.147.1" , 1 ) ;
ipMap. put ( "192.168.147.2" , 1 ) ;
ipMap. put ( "192.168.147.3" , 1 ) ;
}
Integer pos = 0 ;
public String RoundRobin ( ) {
Map < String , Integer > ipServerMap= new ConcurrentHashMap < > ( ) ;
ipServerMap. putAll ( ipMap) ;
Set < String > ipset= ipServerMap. keySet ( ) ;
ArrayList < String > iplist= new ArrayList < String > ( ) ;
iplist. addAll ( ipset) ;
String serverName= null ;
synchronized ( pos) {
if ( pos>= ipset. size ( ) ) {
pos= 0 ;
}
serverName= iplist. get ( pos) ;
pos ++ ;
}
return serverName;
}
public static void main ( String [ ] args) {
TestRoundRobin testRoundRobin = new TestRoundRobin ( ) ;
for ( int i= 0 ; i< testRoundRobin. ipMap. size ( ) ; i++ ) {
String serverIp= testRoundRobin. RoundRobin( ) ;
System . out. println ( serverIp) ;
}
}
}