The official account of WeChat:Love to ask CTO
Professional programming Q & a community
www.askcto.com
Introduction to jedis
Redis not only uses commands to operate, but also uses program client to operate. Now basically, the mainstream languages have client support, such as Java, C, C #, C + +, PHP, go, etc
Some Java clients are listed in the official website, and the one most used in enterprises is jedis.
Basic use
public class JedisTest {
@Test
public void testJedis() {
//Create a connection to jedis
Jedis jedis = new Jedis("192.168.232.128", 6379);
//Execute the redis command
jedis.set("k1", "jedis");
//Value from redis
String result = jedis.get("k1");
//Print results
System.out.println(result);
//Close the connection
jedis.close();
}
}
View the results after running:
jedis
After the jedis object is constructed, the bottom layer of jedis will open a socket channel to connect with the redis service
The frequent creation and destruction of jedis objects has a great impact on performance.
Use of connection pool
@Test
public void testJedisPool() {
JedisPoolConfig config = new JedisPoolConfig();
//Controls the maximum number of jedis instances with idle status in a pool
config.setMaxIdle(8);
//Maximum connections
config.setMaxTotal(18);
//Create a connection pool object
JedisPool jedisPool = new JedisPool(config,"192.168.232.128", 6379);
//Get connections from connection pool
Jedis jedis = jedisPool.getResource();
String result = jedis.get("k1") ;
System.out.println(result);
//Close the connection
jedis.close();
//Close the connection池
jedisPool.close();
}
View the results after running:
jedis
Jedis connect cluster
@Test
public void testJedisCluster() {
//Creating a jediscluster object
Set<HostAndPort> nodes = new HashSet<>();
nodes.add(new HostAndPort("192.168.232.128", 7001));
nodes.add(new HostAndPort("192.168.232.128", 7002));
nodes.add(new HostAndPort("192.168.232.128", 7003));
nodes.add(new HostAndPort("192.168.232.128", 7004));
nodes.add(new HostAndPort("192.168.232.128", 7005));
nodes.add(new HostAndPort("192.168.232.128", 7006));
JedisCluster cluster = new JedisCluster(nodes);
//The API method of cluster object is used to add and query redis cluster
cluster.set("c1", "jedisCluster");
System.out.println(cluster.get("c1"));
//Release resources
cluster.close();
}