Redis demo
程序员文章站
2022-03-25 18:07:26
...
下载jedis包(操作Redis的java API)
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>
1.连接redis的简单示例
package mytest.jedis; import redis.clients.jedis.Jedis; /** * Hello world! * */ public class SimpleDemo { public static void main( String[] args ) { Jedis j = new Jedis("master",6380);//创建连接,耗费资源 String value = j.get("name"); System.out.println( "Hello World! "+value ); j.close(); } }
2.从连接池中取出连接
package mytest.jedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class JedisPoolDemo { public static void main(String[] args) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(50); JedisPool pool = new JedisPool(config, "master", 6380); Jedis jedis = pool.getResource(); String value = jedis.get("name"); System.out.println("--"+value); } }
3.分片的连接池
客户不必关心数据存储在哪台redis服务器(是端口为6379的服务器,还是端口为6380的服务器)
package mytest.jedis; import java.util.ArrayList; import java.util.List; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; public class ShardJedisDemo { public static void main(String[] args) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(50); List<JedisShardInfo> list = new ArrayList<JedisShardInfo>(); JedisShardInfo info1 = new JedisShardInfo("master",6379);//redis分片信息 JedisShardInfo info2 = new JedisShardInfo("master",6380);//redis分片信息 list.add(info1); list.add(info2); ShardedJedisPool pool = new ShardedJedisPool(config, list);//分片的池 ShardedJedis sJedis = pool.getResource(); sJedis.set("name2", "zhaowu2"); sJedis.set("age2", "12"); sJedis.set("gender2", "male"); //String age = sJedis.get("age"); //System.out.println("name="+name+";age="+age); System.out.println("name="+sJedis.get("name")+";gender="+sJedis.get("gender")+";age="+sJedis.get("age")); System.out.println("name2="+sJedis.get("name2")+";gender2="+sJedis.get("gender2")+";age2="+sJedis.get("age2")); sJedis.close(); pool.close(); } }