简体   繁体   English

Spring bean线程对Jedis安全吗?

[英]Is Spring bean thread safe for Jedis?

We are not too sure if we apply Jedis pool correctly in order to achieve a Jedis thread-safe using Spring beans 我们不太确定是否正确使用Jedis池以使用Spring bean实现Jedis线程安全

<bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager>
<property name="pool">
    <bean class="redis.clients.jedis.JedisPool">
        <constructor-arg value="redis://localhost:1234/1" />
    </bean>
</property>

private JedisPool pool;

public void setPool(JedisPool pool) {
    this.pool = pool;
}

private boolean exists(String key) {
    Jedis jedis = pool.getResource();
    try {
        return jedis.exists(key);
    } finally {
        jedis.close();
    }
}

Did we implement Jedis pool correctly? 我们是否正确实施Jedis池? does this code perform a thread-safe Jedis? 此代码是否执行线程安全的Jedis? If not, how should we use spring beans to make jedis threadsafe? 如果没有,我们应该如何使用弹簧豆使jedis线程安全?

Please advise.. Thanks 请指教..谢谢

What he is trying to say is that create the pool in a spring singleton bean Or class with static method for accessing pool. 他想说的是在spring singleton bean Or class with static methodspring singleton bean Or class with static method中创建池以访问池。 If you do either of it, you should be fine. 如果您选择其中任何一个,都应该没问题。 What you have done in the code is that You are creating a pool for each instance of the ResourceManager and it can be improved like the following. 您在代码中所做的是,您正在为ResourceManager的每个实例创建一个池,并且可以如下进行改进。

@Scope("singleton")
public class ResourceManager {

    private JedisPool pool ;

    public ResourceManager(){
        pool = new JedisPool(new JedisPoolConfig(), "localhost");       
    }

    private boolean exists(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.exists(key);
        } finally {
            jedis.close();
        }
    }

}

Your application context will not have the inner bean. 您的应用程序上下文将没有内部bean。

<bean id="redisOnlineManager" class="com.app.online.RedisOnlineManager/><!-- you dont need this in the application context if you are using annotations -->

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM