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

org.bdware.doip.cluster.client.pooledClient.DoaClusterPooledClient Maven / Gradle / Ivy

The newest version!
package org.bdware.doip.cluster.client.pooledClient;

import org.bdware.doip.codec.doipMessage.DoipMessage;
import org.bdware.doip.endpoint.client.ClientConfig;
import org.bdware.doip.endpoint.client.DoipMessageCallback;

import java.util.LinkedHashMap;
import java.util.Map;

public class DoaClusterPooledClient {

    // 设置缓存的最大容量
    private static final int MAX_CACHED_CHANNELS = 10000; // 设置为10000
    // 这里的key其实是对应的地址信息(serverEndpoint即由host port构造而成,自定义实现)
    // 使用LinkedHashMap实现LRU缓存
    static Map clientForSwitchConcurrentHashMap = new LinkedHashMap(MAX_CACHED_CHANNELS, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            // 当缓存超过最大容量时,移除最老的条目
            return size() > MAX_CACHED_CHANNELS;
        }
    };
    //    public static ConcurrentHashMap clientForSwitchConcurrentHashMap = new ConcurrentHashMap<>();
    int MAX_CONNECTIONS;


    public DoaClusterPooledClient(int maxConnections) {
        this.MAX_CONNECTIONS = maxConnections;
    }

    public boolean isStored(ServerEndpoint k) {
        if (this.clientForSwitchConcurrentHashMap.get(k) != null) return true;
        return false;
    }

    public void addClient(ServerEndpoint k, PooledClientByFixedChannelPool client) {
        this.clientForSwitchConcurrentHashMap.put(k, client);
    }

    public void sendMessage(String host,int port,DoipMessage msg, DoipMessageCallback callback) throws Exception {
        //这里需要通过host和port去构造endpoint的位置信息
        ServerEndpoint endpoint = new ServerEndpoint(host,port);
        //如果之前已经存过了
        if (isStored(endpoint)) {
            clientForSwitchConcurrentHashMap.get(endpoint).sendMessage(msg, callback);
        } else {
            PooledClientByFixedChannelPool client = new PooledClientByFixedChannelPool(ClientConfig.fromUrl("tcp://" + host + ":" + port), MAX_CONNECTIONS);
//                    PooledClient client = new PooledClient(ClientConfig.fromUrl("tcp://" + host + ":" + port), MAX_CONNECTIONS);
            addClient(endpoint, client);
            client.sendMessage(msg, callback);
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy