Redis resources are not released.

Source: Internet
Author: User

Redis resources are not released.

I. Causes of unreleased redis resources:

When I modified an old program N years ago, I accidentally killed the redis release,

if (jedis != null) {    if (!isInProcess) {        jedis.del(currentPageRunControlRedisKey);    }    JedisUtil.getInstance().closeJedis(jedis);}

 

After the program is called for a while, the redis connection cannot be obtained. The exception is as follows:

redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the poolat redis.clients.util.Pool.getResource(Pool.java:42)

 

Compare the code, locate the problem, and fix the problem.

 

Ii. analyze the cause of the error afterwards:

1. Lack of knowledge about redis.

2. From the perspective of integrating redis with java, my cognition is as follows:

2.1. SelectSpring-data-redisIntegration. Currently, our osp framework supports this method. my current project is in use (po service ).

Use RedisTemplate after integration.

Benefit: spring helps you manage redis connection acquisition and release. We only need to pay attention to our own business.

Disadvantage: it is limited to the spring framework. Other problems are not found yet...

2.2. NoSpring-data-redisIntegration: use the original jedis to operate it. Another old project of mine is in use (timed tasks pull product materials ).

Write a class to obtain the JedisPool. For redis operations, remember to release the connection back to the connection pool after the operation is complete. Otherwise, this problem will occur.

Benefits: more flexible operations, not limited to spring.

Disadvantage: error-prone.

 

3. improvement:

If the resources are not released, it is best to encapsulate uniform methods in io operations and db operations to ensure that the resources are released at the end.

For redis, refer to spring's redisTemplate,

Encapsulate a redis tool class to encapsulate a method for each type of redis operation. After the operation, the resource is released back to the connection pool to avoid forgetting to release redis.

Sample Code:

1 import org. apache. commons. logging. log; 2 import org. apache. commons. logging. logFactory; 3 import redis. clients. jedis. jedis; 4 import redis. clients. jedis. jedisPool; 5 import redis. clients. jedis. jedisPoolConfig; 6 import java. util. map; 7 import java. util. concurrent. concurrentHashMap; 8 9/** 10 * Description: JedisUtil 11 * Author: 12 */13 public class JedisUtil {14 15 private static final Log logger = LogF Acloud. getLog (JedisUtil. class); 16 17 // Redis Server IP 18 private static String IP = "127.0.0.1"; 19 20 // Redis PORT 21 private static int PORT = 6379; 22 23 // maximum number of available connection instances. The default value is 8. 24 // if the value is-1, no restriction is imposed. If maxActive jedis instances have been allocated to the pool, then, the pool status is exhausted (exhausted ). 25 private static int MAX_ACTIVE = 64; 26 27 // control the maximum number of idle (idle) jedis instances in a pool. The default value is 8. 28 private static int MAX_IDLE = 20; 29 30 // 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 directly; 31 private static int MAX_WAIT = 3000; 32 33 private static int TIMEOUT = 3000; 34 35 // when a jedis instance is in borrow, whether to perform the validate operation in advance; if it is true, the jedis instance is available; 36 private static boolean TEST_ON_BORROW = true; 37 38 // when returning to the pool, whether to perform the validate operation in advance; 39 private static boolean TEST_ON_RETURN = true; 40 41 private static Map <String, JedisPool> maps = new ConcurrentHashMap <S Tring, JedisPool> (); 42 43 44 private JedisUtil () {45} 46 47/*** 48 * class-level internal class, that is, static member internal class, the instance of this internal class has no binding relationship with the instance of the external class, and is loaded only when it is called, thus implementing delayed loading. 49 */50 private static class RedisUtilHolder {51 private static JedisUtil instance = new JedisUtil (); 52} 53 54/** 55 * When the getInstance method is called for the first time, it reads RedisUtilHolder for the first time. instance, causing the RedisUtilHolder class to be initialized. When this class is loaded and initialized, it will initialize its 56 * Static State domain to create a RedisUtil instance, because it is a static domain, it will only be initialized once when the Virtual Machine loads the class, and the virtual machine will ensure its thread security. The advantage of this mode is that the getInstance method is not synchronized, 57 * and only executes access to a domain. Therefore, delayed initialization does not increase access costs. 58 */59 public static JedisUtil getInstance () {60 return RedisUtilHolder. instance; 61} 62 63/** 64 * Get the connection pool. 65 */66 private JedisPool getPool (String ip, int port) {67 String key = ip + ":" + port; 68 JedisPool pool = null; 69 if (! Maps. containsKey (key) {// determines whether the connection pool exists based on the ip address and port. 70 JedisPoolConfig config = new JedisPoolConfig (); 71 config. setMaxTotal (MAX_ACTIVE); 72 config. setMaxIdle (MAX_IDLE); 73 config. setMaxWaitMillis (MAX_WAIT); 74 config. setTestOnBorrow (TEST_ON_BORROW); 75 config. setTestOnReturn (TEST_ON_RETURN); 76 try {77 pool = new JedisPool (config, ip, port, TIMEOUT); 78 maps. put (key, pool); 79} catch (Exception e) {80 Logger. error ("Redis connection pool initialization exception:", e); 81} 82} else {83 pool = maps. get (key); 84} 85 return pool; 86} 87 88/** 89 * get Jedis instance 90 */91 public Jedis getJedis () {92 Jedis jedis = null; 93 try {94 jedis = getPool (IP, PORT ). getResource (); 95} catch (Exception e) {96 logger. error ("error in obtaining Jedis instance:", e); 97 // destroy object 98 getPool (IP, PORT ). returnBrokenResource (jedis); 99} 100 return jedis; 101} 102 103 /** 104 * release jedis resources to connection pool 105 */106 public void returnResource (final Jedis jedis) {107 if (jedis! = Null) {108 getPool (IP, PORT ). returnResource (jedis); 109} 110} 111 112/** 113 * get Data 114 */115 public Object get (String key) {116 Object value = null; 117 Jedis jedis = null; 118 try {119 jedis = getJedis (); 120 value = jedis. get (key); 121} catch (Exception e) {122 logger. warn ("data retrieval exception:", e); 123} finally {124 // return to connection pool 125 returnResource (jedis); 126} 127 return value; 128} 129 130 public static void main (String [] args) {131 Object val = JedisUtil. getInstance (). get ("redisKey"); 132 System. out. println (val); 133} 134 135}

Iv. redis concept:

Redis is a key-value storage system. Similar to Memcached, Memcached supports more storage value types, including string, list, set, and zset) and hash (hash type ). These data types support push/pop, add/remove, Intersection Set and difference set, and more abundant operations, and these operations are atomic. On this basis, redis supports sorting in different ways. Like memcached, data is cached in the memory to ensure efficiency. The difference is that redis periodically writes the updated data to the disk or writes the modification operation to the append record file, and on this basis implements master-slave (master-slave) synchronization.

 

V. Concept of database connection pool:

The database connection pool is responsible for allocating, managing, and releasing database connections. It allows applications to repeat an existing database connection instead of re-establishing one; release the database connection with idle time exceeding the maximum idle time to avoid database connection omissions caused by the absence of the database connection. This technology can significantly improve the performance of database operations.

 

Vi. References:

Http://www.cnblogs.com/linjiqin/archive/2013/06/14/3135248.html

Http://www.sjsjw.com/kf_www/article/70_11941_26800.asp

Http://www.cnblogs.com/tankaixiong/p/3660075.html

Http://blog.csdn.net/truong/article/details/46711045

Http://my.oschina.net/ydsakyclguozi/blog/465859

Http://blog.csdn.net/aacm1992/article/details/21977237

Http://www.cnblogs.com/jifeng/p/4676863.html

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.