All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.taotao.boot.sms.common.loadbalancer.HashLoadBalancer Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2020-2030, Shuigedeng ([email protected] & https://blog.taotaocloud.top/).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.taotao.boot.sms.common.loadbalancer;

import java.util.List;
import java.util.Random;

/**
 * hash Load Balancer
 *
 * @author shuigedeng
 * @version 2022.04
 * @since 2022-04-27 17:52:51
 */
public class HashLoadBalancer extends AbstractLoadBalancer {

    /** instantiation Load Balancer with CopyOnWriteArrayList */
    public HashLoadBalancer() {
        super();
    }

    /**
     * instantiation Load Balancer with appoint list
     *
     * @param targetList target object list
     */
    public HashLoadBalancer(List> targetList) {
        super(targetList);
    }

    @Override
    protected T choose0(List> activeTargetList, C chooseReferenceObject) {
        if (chooseReferenceObject == null) {
            Random random = new Random();

            TargetWrapper wrapper = activeTargetList.get(random.nextInt(activeTargetList.size()));

            return wrapper == null ? null : wrapper.getTarget();
        } else {
            int hashCode = chooseReferenceObject.hashCode();
            int size = activeTargetList.size();
            int position = hashCode % size;

            TargetWrapper wrapper = activeTargetList.get(position);

            return wrapper == null ? null : wrapper.getTarget();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy