1. environment
Need spring.jar, Common-pool.jar.jedisjar
2. Introduction
Sharding (shardedjedis) distributes different keys to different Redis servers for horizontal scaling Purposes.
3. Configure Application.xml
<!--loading Redis profiles--
<location="classpath:redis.properties"/>
<!--connection Pool configuration--
<BeanID= "poolcfg"class= "redis.clients.jedis.JedisPoolConfig"> < propertyname= "maxtotal"value= "${redis.pool.maxactive}" /> < propertyname= "maxidle"value= "${redis.pool.maxidle}" /> < propertyname= "minidle"value= "1"/> < propertyname= "maxwaitmillis"value= "${redis.pool.maxwait}" /> < propertyname= "testonborrow"value= "true"/> < propertyname= "testonreturn"value= "true"/> </Bean>
<!--port Remember to specify type int--<BeanID= "shardedjedispool"class= "redis.clients.jedis.ShardedJedisPool"> <Constructor-argIndex= "0"ref= "poolcfg"></Constructor-arg> <Constructor-argIndex= "1"> <List> <Beanname= "master"class= "redis.clients.jedis.JedisShardInfo"> <Constructor-argIndex= "0"value= "${redis1.ip}"></Constructor-arg> <Constructor-argIndex= "1"value= "${redis1.port}"type= "int"></Constructor-arg> < propertyname= "password"value= "${redis2.auth}"/> </Bean> <Beanname= "slaver"class= "redis.clients.jedis.JedisShardInfo"> <Constructor-argIndex= "0"value= "${redis2.ip}"></Constructor-arg> <Constructor-argIndex= "1"value= "${redis2.port}"type= "int"></Constructor-arg> < propertyname= "password"value= "${redis2.auth}"/> </Bean> </List> </Constructor-arg></Bean>
4. Get resources, Release resources
@Repository ("jedisdataresource") public classJedisdataresourceimplImplementsJedisdataresource{@Resource (name= "shardedjedispool") PrivateShardedjedispool sharededjedispool; @Override publicShardedjedis getresource () {shardedjedis Shardedjedis=NULL; Try{shardedjedis=Sharededjedispool.getresource (); returnshardedjedis; } Catch(Exception E) {if(NULL!=Sharededjedispool) Sharededjedispool.close (); } return NULL; } @Override public voidReturnresource (shardedjedis Shardedjedis) {if(shardedjedis!=NULL) Shardedjedis.close (); } }
5.dao Layer
public Interface Userredisdao { /** Get user name * /double getusername (String Key) ; }
@Repository ("userredisdao") public classUserredisdaoimplImplementsUserredisdao{@ResourcePrivateJedisdataresource jedisdataresource;@Override public Stringgetusername (String key) {shardedjedis Shardedjedis=Jedisdataresource.getresource (); if(NULL==Shardedjedis)returnNull; Try { returnShardedjedis.get (key); } Catch(Exception e) {e.printstacktrace (); } finally{jedisdataresource.returnresource (shardedjedis); } }
}
6.service
public Interface commodityredisservice { string getusername (string key); }
@Service ("userredisservice")publicclassimplements userredisservice{ @Autowired Private Userredisdao userredisdao; @Override public string increasecollectnum (string key) { return userredisdao.getusername (key);} }
Spring Integrated Redis