Skip to content

Commit

Permalink
负载均衡
Browse files Browse the repository at this point in the history
  • Loading branch information
mwq0106 committed Oct 12, 2020
1 parent b66c480 commit 5df7640
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 7 deletions.
2 changes: 1 addition & 1 deletion client/src/main/java/com/hirpc/loadbalance/Balancer.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public interface Balancer {

/**
* 从候选地址<code>candidates</code>中根据一定的负载均衡算法选出一台服务器的地址
* 从候选地址 candidates 中根据一定的负载均衡算法选出一台服务器的地址
*
* @param service 服务
* @param candidates 服务的候选地址
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,10 @@ private long hash(String key) {
| ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF);

long truncateHashCode = hashCode & 0xffffffffL;
return truncateHashCode;
return hashCode & 0xffffffffL;
}

public RpcClientHandler doRoute(String serviceKey, List<RpcClientHandler> handlers) {
private RpcClientHandler doRoute(String serviceKey, List<RpcClientHandler> handlers) {

// ------A1------A2-------A3------
// -----------J1------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
Expand All @@ -15,13 +16,15 @@
*/
public class RoundRobinBalancer implements Balancer {

private volatile Map<String, AtomicInteger> requestMap = new HashMap<>();
private volatile Map<String, AtomicInteger> requestMap = new ConcurrentHashMap<>();
@Override
public RpcClientHandler elect(String service, List<RpcClientHandler> candidates) {
if (!requestMap.containsKey(service)) {
AtomicInteger lastIndex = requestMap.get(service);
if (lastIndex == null) {
requestMap.put(service, new AtomicInteger(0));
lastIndex = requestMap.get(service);
}
int index = requestMap.get(service).getAndAdd(1) % candidates.size();
int index = lastIndex.getAndAdd(1) % candidates.size();

return candidates.get(index);
}
Expand Down

0 comments on commit 5df7640

Please sign in to comment.