Using Redis in Java:
1: Brief description of the relationship between Jedis and Redis:
Jedis Brief Description:
That is: Jedis is the bridge-----client that connects Redis
Name of Jedis: Java redis---->jedis
Second, let us take a look at the specific use of Jedis:
Required JAR Packages:
2-1: Single-instance connection:
1 Public classRedisdemo {2 Public Static voidMain (string[] args) {3Jedis Jedis =NewJedis ("39.106.19.224", 6379);
Jedis.set ("Hello", "Javaredis");4String Hello = jedis.get ("Hello");5 System.out.println (hello);
Jedis.close ();6 }7 8}
2-2: Connection Pool Connection:
Common APIs:
1 Public voidJedispool () {2 //To create a connection Pool configuration object:3Jedispoolconfig JPC =Newjedispoolconfig ();4 //Set maximum idle count5Jpc.setmaxidle (30);6 //Set minimum idle count:7Jpc.setminidle (10);8 //set maximum number of connections9Jpc.setmaxtotal (50);Ten //Create Connection Pool object host: Connect to the Redis host IP; port:redis default port OneJedispool Jedispool =NewJedispool (JPC, "127.0.0.1", 6379); A //Get Connection Resources -Jedis resource =Jedispool.getresource (); - //put value: theResource.set ("Key", "Hello Redis"); - //Value: -Resource.get ("Key"); -}
Tool classes for using Redis in Java:
Jedispoolutils:
1 ImportRedis.clients.jedis.Jedis;2 ImportRedis.clients.jedis.JedisPool;3 ImportRedis.clients.jedis.JedisPoolConfig;4 5 Importjava.io.IOException;6 ImportJava.io.InputStream;7 Importjava.util.Properties;8 9 Public classJedispoolutils {Ten Private StaticJedispool pool =NULL; One A Static { - //Load configuration file -InputStream in = Jedispoolutils.class. getClassLoader (). getResourceAsStream ("Redis.properties"); theProperties Pro =NewProperties (); - Try { - pro.load (in); -}Catch(IOException e) { + e.printstacktrace (); - } + //Get Pool Object AJedispoolconfig Poolconfig =Newjedispoolconfig (); atPoolconfig.setmaxidle (Integer.parseint (Pro.get ("Redis.maxidle"). ToString ()));//Maximum Idle Count -Poolconfig.setminidle (Integer.parseint (Pro.get ("Redis.minidle"). ToString ()));//minimum number of idle -Poolconfig.setmaxtotal (Integer.parseint (Pro.get ("Redis.maxtotal"). ToString ()));//Maximum number of connections -Pool =NewJedispool (Poolconfig, Pro.getproperty ("Redis.url"), Integer.parseint (Pro.get ("Redis.port"). toString () )); - } - in //ways to get Jedis resources - Public StaticJedis Getjedis () { to returnPool.getresource (); + } - the //stored value: * Public Static voidSetpool (String key,string value) { $ Getjedis (). Set (Key,value);Panax Notoginseng } - //Value: the Public Static voidGetpool (String key) { + Getjedis (). get (key); A } the Public Static voidMain (string[] args) { +Setpool ("Key", "value"); -Getpool ("Key"); $ } $}
Redis.properties:
1 #最大闲置数 2 redis.maxidle=30 3#最小闲置数 4 redis.minidle=10 5#最大连接数 6 redis.maxtotal=100 7#连接安装redis服务器的IP地址 8 redis.url=192.168.186.131 9 #redis的默认端口 ten redis.port=6379
Using Redis in Java