如何为第三方应用程序创建一个连接池/一次?

问题描述 投票:1回答:1

我正在使用JAVA / Spring MVC,我需要为我的应用程序中的第三方应用程序集成创建一个连接池,因为当我尝试多次连接它时,我的应用程序和服务器系统使用100%RAM。

在这里我不得不问题,当用户开始多次击中特定方法(callGenerationService())时,我的堆内存(RAM空间)增加并变为100%并且应用程序因为连接多次连接第三方应用程序而变慢?在这里,我只需要创建一次connection并多次获得它。我的连接在哪里,

public class ClickToCallServiceImpl implements ClickToCallServiceInterface {
Client client = null;
@Override
public ClickToCall callGenerationService(ClickToCall clickToCall) {
     client = new Client();
     client.connect("127.0.0.1", 8021 , "password", 10); //Every time Connection Connect.
     client.setEventSubscriptions("plain", "all");
     // client.sendSyncApiCommand("",""); //here i run command on every hit like.
    client.sendSyncApiCommand(clickToCall.command1, clickToCall.command2);
    client.close();
}
}

这里的'ClickToCall'是一个带有变量setter和getters的@Component Bean / POJO类。

有没有,我们如何为上面的连接创建一个connection (either pool or only once connect),我连接一次并多次点击clickToCall.Command1 and clickToCall.Command2并使用更少的RAM?提前致谢。

java spring spring-mvc connection-pooling
1个回答
1
投票

请注意,我不是freeswitch esl的专家,因此您必须正确检查代码。不管怎样,这就是我要做的。

首先,我为客户创建一个工厂

public class FreeSwitchEslClientFactory extends BasePooledObjectFactory<Client> {

    @Override
    public Client create() throws Exception {
        //Create and connect: NOTE I'M NOT AN EXPERT OF ESL FREESWITCH SO YOU MUST CHECK IT PROPERLY
        Client client = new Client();
        client.connect("127.0.0.1", 8021 , "password", 10);
        client.setEventSubscriptions("plain", "all");
        return client;
    }

    @Override
    public PooledObject<Client> wrap(Client obj) {

        return new DefaultPooledObject<Client>(obj);
    }
}

然后我创建了一个可共享的GenericObjectPool

@Configuration
@ComponentScan(basePackages= {"it.olgna.spring.pool"})
public class CommonPoolConfig {

    @Bean("clientPool")
    public GenericObjectPool<Client> clientPool(){
        GenericObjectPool<Client> result = new GenericObjectPool<Client>(new FreeSwitchEslClientFactory());
        //Pool config e.g. max pool dimension
        result.setMaxTotal(20);
        return result;
    }
}

最后,我使用创建的池来获取客户端obj:

@Component
public class FreeSwitchEslCommandSender {

    @Autowired
    @Qualifier("clientPool")
    private GenericObjectPool<Client> pool;

    public void sendCommand(String command, String param) throws Exception{
        Client client = null;
        try {
            client = pool.borrowObject();
            client.sendSyncApiCommand(command, param);
        } finally {
            if( client != null ) {
                client.close();
            }
            pool.returnObject(client);
        }
    }
}

我没有测试(也因为我不能),但它应该工作。无论如何,我祈祷你正确检查配置。我不知道是否可以始终创建客户端对象并进行连接,或者如果要在发送命令时更好地连接

我希望它有用

编辑信息

对不起我早点出错了。您必须将客户端返回到我更新了FreeSwitchEslCommandSender类的池中

安杰洛

© www.soinside.com 2019 - 2024. All rights reserved.