This article shares the specific code of Jedis operating the Redis database for your reference. The specific content is as follows
I won't write the introduction about NoSQL, just enter the code
The first step is guided, not much
Basic operations:
package demo;import org.junit.Test;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class Demo { // Access the Redis database through a Java program @Test public void test1() { // Obtain the connection object Jedis jedis = new Jedis("localhost", 6379); // Store and obtain the data jedis.set("username", "yiqing"); String username = jedis.get("username"); System.out.println(username); } // Jedis connection pool gets the jedis connection object @Test public void test2() { // Configure and create redis connection pool JedisPoolConfig poolconfig = new JedisPoolConfig(); // Maximum (small) idle number poolconfig.setMaxIdle(30); poolconfig.setMinIdle(10); // Maximum number of connections poolconfig.setMaxTotal(50); JedisPool pool = new JedisPool(poolconfig, "localhost", 6379); // Get resources Jedis jedis = pool.getResource(); jedis.set("username", "yiqing"); String username = jedis.get("username"); System.out.println(username); // Close the resource jedis.close(); // The connection pool will not be closed during development// pool.close(); }}Note: If the run fails, there is only one reason: Redis is not turned on:
OK, we can use visual tools to observe:
Save successfully! !
Next:
We need to extract a tool class for easy operation:
package demo;import java.io.IOException;import java.io.InputStream;import java.util.Properties;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtils { private static JedisPool pool = null; static { // Load the configuration file InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties"); Properties pro = new Properties(); try { pro.load(in); } catch (IOException e) { e.printStackTrace(); } // Get the pool object JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));// Maximum idle number poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));// Minimum idle number poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));// Maximum number of connections pool = new JedisPool(poolConfig, pro.getProperty("redis.url"), Integer.parseInt(pro.get("redis.port").toString())); } // Get Jedis resources public static Jedis getJedis() { return pool.getResource(); }}Create a new file under src: redis.properties:
redis.maxIdle=30redis.minIdle=10redis.maxTotal=100redis.url=localhostredis.port=6379
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.