Initial code import
[msb/apigateway.git] / apiroute / apiroute-service / src / main / java / org / openo / msb / wrapper / util / JedisUtil.java
1 /**\r
2 * Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)\r
3 *\r
4 * Licensed under the Apache License, Version 2.0 (the "License");\r
5 * you may not use this file except in compliance with the License.\r
6 * You may obtain a copy of the License at\r
7 *\r
8 * http://www.apache.org/licenses/LICENSE-2.0\r
9 *\r
10 * Unless required by applicable law or agreed to in writing, software\r
11 * distributed under the License is distributed on an "AS IS" BASIS,\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13 * See the License for the specific language governing permissions and\r
14 * limitations under the License.\r
15 */\r
16 \r
17 package org.openo.msb.wrapper.util;\r
18 \r
19 import java.io.BufferedInputStream;\r
20 import java.io.File;\r
21 import java.io.FileInputStream;\r
22 import java.util.PropertyResourceBundle;\r
23 import java.util.ResourceBundle;\r
24 \r
25 import org.apache.commons.lang3.StringUtils;\r
26 import org.slf4j.Logger;\r
27 import org.slf4j.LoggerFactory;\r
28 \r
29 import redis.clients.jedis.Jedis;\r
30 import redis.clients.jedis.JedisPool;\r
31 import redis.clients.jedis.JedisPoolConfig;\r
32 \r
33 \r
34 \r
35 public final class JedisUtil {\r
36         private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class);\r
37         private static String host = "127.0.0.1";\r
38         private static int port = 6379;\r
39         private static int connectionTimeout = 2000;\r
40         private static int DEFAULT_DB_INDEX = 0;\r
41 \r
42         private static JedisPool jedisPool = null;\r
43         \r
44         public static String serverIp="127.0.0.1";\r
45         \r
46         public static int serverPort=10080;\r
47         \r
48         public static String propertiesName="redis.properties";\r
49             \r
50         public static String propertiesPath="";\r
51 \r
52         \r
53         \r
54 public static void main(String[] args) {\r
55         \r
56 }\r
57 \r
58         private JedisUtil() {\r
59                 // private constructor\r
60 \r
61         }\r
62         \r
63         private static void initialPool() {\r
64                 try {\r
65                     JedisPoolConfig config = new JedisPoolConfig();\r
66                         \r
67 //                      String pathtest=JedisUtil.class.getResource("").getPath();\r
68 //                      String path ="/"+ pathtest.substring(0, pathtest.indexOf("assembly")).replace("file:/", "") +"assembly/"+defaultWorkspace;\r
69                 \r
70                         File propertiesFile = new File(propertiesPath);\r
71                         \r
72                            if (propertiesFile.exists()) {\r
73                                   \r
74                                  \r
75                                  BufferedInputStream inputStream =new BufferedInputStream(new FileInputStream(propertiesPath));  \r
76                                  ResourceBundle bundle =new PropertyResourceBundle(inputStream);\r
77                                  \r
78                                  if (bundle == null) {\r
79                                                 throw new IllegalArgumentException(\r
80                                                                 "[redis.properties] is not found!");\r
81                                         }\r
82                                  \r
83 \r
84                                         // 设置连接池基本信息\r
85                                         String strHost = bundle.getString("redis.host");\r
86                                         if(StringUtils.isNotEmpty(strHost)){\r
87                                                 host = strHost;\r
88                                         }\r
89                                         String strPort = bundle.getString("redis.port");\r
90                                         if(StringUtils.isNotEmpty(strPort)){\r
91                                                 port = Integer.valueOf(strPort);\r
92                                         }\r
93                                 \r
94                                         \r
95                                         String strTimeout = bundle.getString("redis.connectionTimeout");\r
96                                         if (StringUtils.isNotEmpty(strTimeout) ){\r
97                                                 connectionTimeout = Integer.valueOf(strTimeout);\r
98                                         }\r
99                                         \r
100 //                                      serverIp=bundle.getString("server.ip");\r
101                                         serverPort=Integer.valueOf(bundle.getString("server.port"));\r
102                                         \r
103                                         String strDbIndex = bundle.getString("redis.db_index");\r
104                                         if (StringUtils.isNotEmpty(strDbIndex)) {\r
105                                                 DEFAULT_DB_INDEX = Integer.valueOf(strDbIndex);\r
106                                         }\r
107 \r
108                                         String strMaxTotal = bundle.getString("redis.pool.maxTotal");\r
109                                         if (StringUtils.isNotEmpty(strMaxTotal)) {\r
110                                                 config.setMaxTotal(Integer.valueOf(strMaxTotal));\r
111                                         }\r
112 \r
113                                         String strMaxIdle = bundle.getString("redis.pool.maxIdle");\r
114                                         if (StringUtils.isNotEmpty(strMaxIdle)) {\r
115                                                 config.setMaxIdle(Integer.valueOf(strMaxIdle));\r
116                                         }\r
117 \r
118                                         String strMaxWaitMillis = bundle.getString("redis.pool.maxWaitMillis");\r
119                                         if (StringUtils.isNotEmpty(strMaxWaitMillis)) {\r
120                                                 config.setMaxWaitMillis(Long.valueOf(strMaxWaitMillis));\r
121                                         }\r
122 \r
123                                         String strTestOnBorrow = bundle\r
124                                                         .getString("redis.pool.testOnBorrow");\r
125                                         if (StringUtils.isNotEmpty(strTestOnBorrow)) {\r
126                                                 config.setTestOnBorrow(Boolean.valueOf(strTestOnBorrow));\r
127                                         }\r
128 \r
129                                         String strTestOnReturn = bundle\r
130                                                         .getString("redis.pool.testOnReturn");\r
131                                         if (StringUtils.isNotEmpty(strTestOnReturn)) {\r
132                                                 config.setTestOnReturn(Boolean.valueOf(strTestOnReturn));\r
133                                         }\r
134 \r
135                            }\r
136                         \r
137                                 LOGGER.info("Redis server info: " + host + ":" + port);\r
138                                 LOGGER.info("nginx server info: " + serverIp + ":" + serverPort);\r
139         \r
140                         \r
141 //                      ResourceBundle bundle = ResourceBundle.getBundle("conf.redis");\r
142         \r
143                         jedisPool = new JedisPool(config, host, port, connectionTimeout);\r
144                 } catch (Exception e) {\r
145                         LOGGER.error("Initiate Jedis pool failed!", e);\r
146                 }\r
147         }\r
148         /**\r
149          * From the connection pool to obtain jedis instance, use the default database index number 0\r
150          * @return\r
151          */\r
152         public synchronized static Jedis borrowJedisInstance() {\r
153                 if (jedisPool == null) {\r
154                         initialPool();\r
155                 }\r
156                 try {\r
157                         if (jedisPool != null) {\r
158                                 Jedis resource = jedisPool.getResource();\r
159                                 resource.select(DEFAULT_DB_INDEX);\r
160                                 return resource;\r
161                         } else {\r
162                                 return null;\r
163                         }\r
164                 } catch (Exception e) {\r
165                         LOGGER.error("Get Jedis from pool failed!", e);\r
166                         return null;\r
167                 }\r
168         }\r
169         /**\r
170          * From the connection pool to obtain jedis instance, using the specified database index number\r
171          * @return\r
172          */\r
173         public synchronized static Jedis borrowJedisInstance(final int dbIndex) {\r
174                 if (jedisPool == null) {\r
175                         initialPool();\r
176                 }\r
177                 try {\r
178                         if (jedisPool != null) {\r
179                                 Jedis resource = jedisPool.getResource();\r
180                                 resource.select(dbIndex);\r
181                                 return resource;\r
182                         } else {\r
183                                 return null;\r
184                         }\r
185                 } catch (Exception e) {\r
186                         LOGGER.error("Get Jedis from pool failed!", e);\r
187                         return null;\r
188                 }\r
189         }\r
190         \r
191         /**\r
192          *  returned to the pool jedis instance\r
193          * @param jedis\r
194          */\r
195         public static void returnJedisInstance(final Jedis jedis) {\r
196                 if (jedis != null) {\r
197                         jedis.close();\r
198                 }\r
199         }\r
200         \r
201         \r
202         /** \r
203         * @Title getJedis \r
204         * @Description TODO(From the connection pool to obtain jedis instance) \r
205         * @throws Exception      \r
206         * @return Jedis    \r
207         */\r
208         public static Jedis getJedis() throws Exception{\r
209              \r
210   \r
211                 Jedis jedis = borrowJedisInstance();\r
212             if (jedis == null) {\r
213                 throw new Exception("fetch from jedis pool failed,null object!");\r
214                 \r
215             }\r
216             \r
217             return jedis;\r
218       \r
219         }\r
220 \r
221 }