jedis是redis的java客户端,spring使用spring-data-redis对其进行集成。
maven导入相关包:
<!-- redis依赖包 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!--spring集成redis--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.8.1.RELEASE</version> </dependency>
ShardedJedisPool是redis集群客户端的对象池,可以通过他来操作ShardedJedis,下面是ShardedJedisPool的xml配置,spring-jedis.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入jedis的properties配置文件 --> <!--如果你有多个数据源需要通过<context:property-placeholder管理,且不愿意放在一个配置文件里,那么一定要加上ignore-unresolvable=“true"--> <context:property-placeholder location="classpath:properties/redis.properties" ignore-unresolvable="true" /> <!--shardedJedisPool的相关配置--> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--新版是maxTotal,旧版是maxActive--> <property name="maxTotal"> <value>${redis.pool.maxActive}</value> </property> <property name="maxIdle"> <value>${redis.pool.maxIdle}</value> </property> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="true"/> </bean> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton"> <constructor-arg index="0" ref="jedisPoolConfig" /> <constructor-arg index="1"> <list> <bean class="redis.clients.jedis.JedisShardInfo"> <constructor-arg name="host" value="${redis.uri}" /> </bean> </list> </constructor-arg> </bean> </beans>
对应的classpath:properties/redis.properties.xml为:
#最大分配的对象数 redis.pool.maxActive=200 #最大能够保持idel状态的对象数 redis.pool.maxIdle=50 redis.pool.minIdle=10 redis.pool.maxWaitMillis=20000 #当池内没有返回对象时,最大等待时间 redis.pool.maxWait=300 #格式:redis://:[密码]@[服务器地址]:[端口]/[db index] redis.uri = redis://:12345@127.0.0.1:6379/0 redis.timeout=30000
简单的操作代码为:
//注入ShardedJedisPool @Autowired private ShardedJedisPool shardedJedisPool; //以键值对形式存入String数据 public String demo_set(){ //获取ShardedJedis对象 ShardedJedis shardJedis = shardedJedisPool.getResource(); //存入键值对 shardJedis.set("key1","hello jedis"); //回收ShardedJedis实例 shardJedis.close(); return "set"; } //根据键值获取数据 public String demo_put(){ ShardedJedis shardedJedis = shardedJedisPool.getResource(); //根据键值获得数据 String result = shardedJedis.get("key1"); shardedJedis.close(); return result; }
原文:http://www.cnblogs.com/red-code/p/6657517.html