引入pom
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.1.0</version> </dependency>
配置 application-context.xml
<!-- redis --> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxTotal" value="100"></property> <property name="maxIdle" value="20" /> <property name="maxWaitMillis" value="3000" /> <!-- <property name="testWhileIdle" value="true"/> --> </bean> <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool" scope="singleton"> <constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg> <constructor-arg name="shards"> <list> <bean class="redis.clients.jedis.JedisShardInfo"> <constructor-arg name="host" value="127.0.0.1" /> <constructor-arg name="port" value="6379" /> </bean> </list> </constructor-arg> </bean>
这样就可以在java文件中用@autowire注入shardedJedisPool
如下面的一个方法为例:
public ZhouyiIndex getZhouyiIndexById(Integer id) { //todo redis ShardedJedis jedis = shardedJedisPool.getResource(); String zhouyiIndexId = jedis.hget("ZhouyiIndexId"+id.toString(), "id"); ZhouyiIndex zhouyiIndex = null; if(zhouyiIndexId!=null) { zhouyiIndex = new ZhouyiIndex( Integer.valueOf(jedis.hget("ZhouyiIndexId"+id.toString(),"id")), jedis.hget("ZhouyiIndexId"+id.toString(),"name"), Integer.valueOf(jedis.hget("ZhouyiIndexId"+id.toString(),"rawId")), Integer.valueOf(jedis.hget("ZhouyiIndexId"+id.toString(),"kongId")), jedis.hget("ZhouyiIndexId"+id.toString(),"info"), jedis.hget("ZhouyiIndexId"+id.toString(),"pic") ); }else { zhouyiIndex = zhouyiIndexMapper.getZhouyiIndexById(id); try { jedis.hset("ZhouyiIndexId"+id.toString(),"id",zhouyiIndex.getId().toString()); jedis.hset("ZhouyiIndexId"+id.toString(),"name",zhouyiIndex.getName()); jedis.hset("ZhouyiIndexId"+id.toString(),"rawId",zhouyiIndex.getRawId().toString()); jedis.hset("ZhouyiIndexId"+id.toString(),"kongId",zhouyiIndex.getKongId().toString()); jedis.hset("ZhouyiIndexId"+id.toString(),"info",zhouyiIndex.getInfo()); jedis.hset("ZhouyiIndexId"+id.toString(),"pic",zhouyiIndex.getPic()); } catch (Exception e) { // TODO: handle exception } } jedis.close(); return zhouyiIndex; }
由shardedJedisPool提供的close方法,不是关闭,而是把资源释放给链接池。这已经在内部封装。
在写入的时候,需要try以下,否则容易爆null错误。