Using Jedis in Java to operate Redis

Source: Internet
Author: User
Tags redis cluster install redis redis server

Using Jedis in Java to operate Redis

Using Java Redis operations need jedis-2.1.0.jar, if you need to use Redis connection pool, but also need commons-pool-1.5.4.jar, the two files to the house of HELP Resources station download:

------------------------------------------ Split line ------------------------------------------

Free in http://linux.bkjia.com/

The username and password are both www.bkjia.com

The specific download directory is used to operate Redis/

For the download method, see

------------------------------------------ Split line ------------------------------------------

Package com. test;

Import java. util. HashMap;
Import java. util. Iterator;
Import java. util. List;
Import java. util. Map;

Import org. junit. Before;
Import org. junit. Test;

Import redis. clients. jedis. Jedis;

Public class TestRedis {
Private Jedis jedis;

@ Before
Public void setup (){
// Connect to the redis server, 192.168.0.100: 6379
Jedis = new Jedis ("192.168.0.100", 6379 );
// Permission Authentication
Jedis. auth ("admin ");
}

/**
* Redis storage string
*/
@ Test
Public void testString (){
// ----- Add data ----------
Jedis. set ("name", "xinxin"); // Add value --> xinxin to key --> name
System. out. println (jedis. get ("name"); // execution result: xinxin

Jedis. append ("name", "is my lover"); // splice
System. out. println (jedis. get ("name "));

Jedis. del ("name"); // deletes a key.
System. out. println (jedis. get ("name "));
// Set multiple key-value pairs
Jedis. mset ("name", "liuling", "age", "23", "qq", "476777XXX ");
Jedis. incr ("age"); // Add 1
System. out. println (jedis. get ("name") + "-" + jedis. get ("age") + "-" + jedis. get ("qq "));

}

/**
* Redis Map operations
*/
@ Test
Public void testMap (){
// ----- Add data ----------
Map <String, String> map = new HashMap <String, String> ();
Map. put ("name", "xinxin ");
Map. put ("age", "22 ");
Map. put ("qq", "123456 ");
Jedis. hmset ("user", map );
// Retrieve the name from the user. The execution result is [minxr] --> note that the result is a generic List.
// The first parameter is the key of the map object stored in redis, followed by the key of the object placed in the map, followed by multiple keys, which are variable parameters
List <String> rsmap = jedis. hmet ("user", "name", "age", "qq ");
System. out. println (rsmap );

// Delete a key value in map
Jedis. hdel ("user", "age ");
System. out. println (jedis. hmet ("user", "age"); // null is returned because it is deleted.
System. out. println (jedis. hlen ("user"); // returns the number of values stored in the key with the key of user 2.
System. out. println (jedis. exists ("user"); // returns true if the key is user.
System. out. println (jedis. hkeys ("user"); // return all keys in the map object
System. out. println (jedis. hvals ("user"); // return all values in the map object

Iterator <String> iter = jedis. hkeys ("user"). iterator ();
While (iter. hasNext ()){
String key = iter. next ();
System. out. println (key + ":" + jedis. hmet ("user", key ));
}
}

/**
* Jedis operation List
*/
@ Test
Public void testList (){
// Remove all contents before starting
Jedis. del ("java framework ");
System. out. println (jedis. lrange ("java framework", 0,-1 ));
// Store three pieces of data to the key java framework first
Jedis. lpush ("java framework", "spring ");
Jedis. lpush ("java framework", "struts ");
Jedis. lpush ("java framework", "hibernate ");
// Retrieve all the data. jedis. lrange is retrieved by range,
// The first is the key, the second is the start position, and the third is the end position. The length obtained by jedis. llen-1 indicates that all
System. out. println (jedis. lrange ("java framework", 0,-1 ));

Jedis. del ("java framework ");
Jedis. rpush ("java framework", "spring ");
Jedis. rpush ("java framework", "struts ");
Jedis. rpush ("java framework", "hibernate ");
System. out. println (jedis. lrange ("java framework", 0,-1 ));
}

/**
* Jedis operation Set
*/
@ Test
Public void testSet (){
// Add
Jedis. sadd ("user", "liuling ");
Jedis. sadd ("user", "xinxin ");
Jedis. sadd ("user", "ling ");
Jedis. sadd ("user", "zhangxinxin ");
Jedis. sadd ("user", "who ");
// Remove noname
Jedis. srem ("user", "who ");
System. out. println (jedis. smembers ("user"); // obtain all added values
System. out. println (jedis. sismember ("user", "who"); // determines whether the who is an element of the user set.
System. out. println (jedis. srandmember ("user "));
System. out. println (jedis. scard ("user"); // returns the number of elements in the set.
}

@ Test
Public void test () throws InterruptedException {
// Jedis sorting
// Note that rpush and lpush here are List operations. Is a two-way linked list (but in terms of performance)
Jedis. del ("a"); // clear the data first, and then add the data for testing.
Jedis. rpush ("a", "1 ");
Jedis. lpush ("a", "6 ");
Jedis. lpush ("a", "3 ");
Jedis. lpush ("a", "9 ");
System. out. println (jedis. lrange ("a", 0,-1); // [9, 3, 6, 1]
System. out. println (jedis. sort ("a"); // [1, 3, 6, 9] // enter the sorting result
System. out. println (jedis. lrange ("a", 0,-1 ));
}

@ Test
Public void testRedisPool (){
RedisUtil. getJedis (). set ("newname", "Chinese test ");
System. out. println (RedisUtil. getJedis (). get ("newname "));
}
}

Redis connection pool:

Package com. test;

Import redis. clients. jedis. Jedis;
Import redis. clients. jedis. JedisPool;
Import redis. clients. jedis. JedisPoolConfig;

Public final class RedisUtil {

// Redis Server IP Address
Private static String ADDR = "192.168.0.100 ";

// Redis port number
Private static int PORT = 6379;

// Access Password
Private static String AUTH = "admin ";

// Maximum number of available connected instances. The default value is 8;
// If the value is-1, there is no restriction. If maxActive jedis instances have been allocated to the pool, the pool status is exhausted (depletion ).
Private static int max_actively = 1024;

// Control the maximum number of idle (idle) jedis instances in a pool. The default value is 8.
Private static int MAX_IDLE = 200;

// Maximum waiting time for available connections, in milliseconds. The default value is-1, indicating that the connection will never time out. If the wait time is exceeded, JedisConnectionException is thrown;
Private static int max_wait= 10000;

Private static int TIMEOUT = 10000;

// Whether to perform the validate operation in advance when a jedis instance is borrow; if it is true, the jedis instance is available;
Private static boolean TEST_ON_BORROW = true;

Private static JedisPool jedisPool = null;

/**
* Initialize the Redis connection pool
*/
Static {
Try {
JedisPoolConfig config = new JedisPoolConfig ();
Config. setMaxActive (MAX_ACTIVE );
Config. setMaxIdle (MAX_IDLE );
Config. setMaxWait (MAX_WAIT );
Config. setTestOnBorrow (TEST_ON_BORROW );
JedisPool = new JedisPool (config, ADDR, PORT, TIMEOUT, AUTH );
} Catch (Exception e ){
E. printStackTrace ();
}
}

/**
* Getting A Jedis instance
* @ Return
*/
Public synchronized static Jedis getJedis (){
Try {
If (jedisPool! = Null ){
Jedis resource = jedisPool. getResource ();
Return resource;
} Else {
Return null;
}
} Catch (Exception e ){
E. printStackTrace ();
Return null;
}
}

/**
* Releasing jedis Resources
* @ Param jedis
*/
Public static void returnResource (final Jedis jedis ){
If (jedis! = Null ){
JedisPool. returnResource (jedis );
}
}
}

You may also like the following articles about Redis. For details, refer:

Install and test Redis in Ubuntu 14.04

Basic configuration of Redis master-slave Replication

Redis cluster details

Install Redis in Ubuntu 12.10 (graphic explanation) + Jedis to connect to Redis

Redis series-installation, deployment, and maintenance

Install Redis in CentOS 6.3

Learning notes on Redis installation and deployment

Redis. conf

Redis details: click here
Redis: click here

This article permanently updates the link address:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.