问题描述:

In a redis java client,I found this:

To use it, init a pool:

JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");

You can store the pool somewhere statically, it is thread-safe.

I just wondering,with spring,how can I store JedisPool statically.

网友答案:

You don't.

In spring it's preferable to define a JedisPool bean and autowire it wherever necessary.

For example, using xml config:

 <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
      <constructor-arg>
           <bean class="redis.clients.jedis.JedisPoolConfig" />
      </consrtuctor-arg>
      <constructor-arg value="localhost" />
 </bean>

and then, inside your beans:

@Autowire
JedisPool jedisPool;

It's even simpler if you use spring java config - you can use exactly the code you posted to define the pool bean:

@Configuration
public class Configuration {

    @Bean
    public JedisPool createJedisPool() { 
        return new JedisPool(new JedisPoolConfig(), "localhost");
    }
}

Also you might want to take a look at spring-data - redis

相关阅读:
Top