redis 簡單使用
/**
* @title: PropertiesUtil.java
* @package:util
* @description:TODO
* @author: [email protected]
* @date: 2017年3月4日 下午10:33:22
* @version:V1.0
*/
package com.djzh.bank.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @ClassName: PropertiesUtil
* @Description: 用一句話描述這個類的作用
* @date 2017年3月4日
* @author [email protected]
* @modify
*/
public class PropertiesUtil {
/** private static logger */
private static final Logger logger = LogManager.getLogger(PropertiesUtil.class);
private static Properties _prop = new Properties();
/**
* 讀取配置文件
*
* @param fileName
*/
public static void readProperties(String fileName) {
try(InputStream in = PropertiesUtil.class.getResourceAsStream("/" + fileName);
BufferedReader bf = new BufferedReader(new InputStreamReader(in))) {
_prop.load(bf);
} catch (IOException e) {
//e.printStackTrace();
logger.error("readProperties Exception |{}",()->e.toString());
logger.debug("failed {}", e);
}
}
/**
* 根據key讀取對應的value
*
* @param key
* @return
*/
public static String getProperty(String key) {
return _prop.getProperty(key);
}
}
2.
package com.djzh.common.utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.djzh.bank.util.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {
private static final Logger logger = LogManager.getLogger(RedisUtils.class);
public static String PROPERTIES_NAME_STR = "redis.properties";
//Redis服務器IP192.168.1.45:6379
private static String ADDR = "";
//Redis的端口號
private static String PORT = "";
//訪問密碼,若你的redis服務器沒有設置密碼,就不需要用密碼去連接
private static String AUTH = "";
//可用連接實例的最大數目,默認值為8;
private static String MAX_TOTAL = "";
//控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。
private static String MAX_IDLE = "";
//等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。
private static String MAX_WAIT = "";
private static String TIMEOUT = "";
//在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/**
* 初始化Redis連接池
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
//獲得屬性值(redis.properties)
PropertiesUtil.readProperties(PROPERTIES_NAME_STR);
MAX_TOTAL = PropertiesUtil.getProperty("MAX_TOTAL");
MAX_IDLE = PropertiesUtil.getProperty("MAX_IDLE");
MAX_WAIT = PropertiesUtil.getProperty("MAX_WAIT");
ADDR=PropertiesUtil.getProperty("ADDR");
PORT=PropertiesUtil.getProperty("PORT");
AUTH=PropertiesUtil.getProperty("AUTH");
TIMEOUT=PropertiesUtil.getProperty("TIMEOUT");
config.setMaxTotal(Integer.valueOf(MAX_TOTAL));
config.setMaxIdle(Integer.valueOf(MAX_IDLE));
config.setMaxWaitMillis(Integer.valueOf(MAX_WAIT));
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDR, Integer.valueOf(PORT), Integer.valueOf(TIMEOUT));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取Jedis實例
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis jedis = jedisPool.getResource();
return jedis;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 釋放jedis資源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
public static void main(String[] args) {
RedisUtils.getJedis().set("xiaomin", "123");
System.out.println(RedisUtils.getJedis().get("xiaomin"));
//簡單的key-value 存儲 jedis.set("redis", "myredis"); System.out.println(jedis.get("redis")); //在原有值得基礎上添加,如若之前沒有該key,則導入該key //之前已經設定了redis對應"myredis",此句執行便會使redis對應"myredisyourredis" jedis.append("redis", "yourredis"); jedis.append("content", "rabbit"); //mset 是設置多個key-value值 參數(key1,value1,key2,value2,...,keyn,valuen) //mget 是獲取多個key所對應的value值 參數(key1,key2,key3,...,keyn) 返回的是個list jedis.mset("name1","yangw","name2","demon","name3","elena"); System.out.println(jedis.mget("name1","name2","name3")); //map Map<String,String> user = new HashMap<String,String>(); user.put("name", "cd"); user.put("password", "123456"); //map存入redis jedis.hmset("user", user); //mapkey個數 System.out.println(String.format("len:%d", jedis.hlen("user"))); //map中的所有鍵值 System.out.println(String.format("keys: %s", jedis.hkeys("user") )); //map中的所有value System.out.println(String.format("values: %s", jedis.hvals("user") )); //取出map中的name字段值 List<String> rsmap = jedis.hmget("user", "name","password"); System.out.println(rsmap); //刪除map中的某一個鍵值 password jedis.hdel("user", "password"); System.out.println(jedis.hmget("user", "name", "password")); //list jedis.del("listDemo"); System.out.println(jedis.lrange("listDemo", 0, -1)); jedis.lpush("listDemo", "A"); jedis.lpush("listDemo", "B"); jedis.lpush("listDemo", "C"); System.out.println(jedis.lrange("listDemo", 0, -1)); System.out.println(jedis.lrange("listDemo", 0, 1)); //set jedis.sadd("sname", "wobby"); jedis.sadd("sname", "kings"); jedis.sadd("sname", "demon"); System.out.println(String.format("set num: %d", jedis.scard("sname"))); System.out.println(String.format("all members: %s", jedis.smembers("sname"))); System.out.println(String.format("is member: %B", jedis.sismember("sname", "wobby"))); System.out.println(String.format("rand member: %s", jedis.srandmember("sname"))); //刪除一個對象 jedis.srem("sname", "demon"); System.out.println(String.format("all members: %s", jedis.smembers("sname")));
}
}
package com.djzh.bank.bj;
import com.djzh.bank.bj.base.BJBaseRequest;import com.djzh.bank.util.PropertiesUtil;import com.djzh.bank.util.XmlModelUtil;
import org.apache.logging.log4j.Logger;import org.apache.logging.log4j.LogManager;
import org.w3c.dom.Document;import org.w3c.dom.Node;
import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;
public class AccountBaseUtil {
public static String PROPERTIES_NAME_STR = "bj_bank.properties"; // 登陸交易URL private static String userLogonUrlStr = "";
// 簽退 URL private static String signOffUrlStr = "";
// 一般交易url private static String ceBankReqUrlStr = "";
// 數據簽名URL private static String dataSignatureUrlStr = "";
private static final Logger logger = LogManager.getLogger(AccountBaseUtil.class);
private AccountBaseUtil() { try {
PropertiesUtil.readProperties(PROPERTIES_NAME_STR); userLogonUrlStr = PropertiesUtil.getProperty("userLogonUrlStr"); signOffUrlStr = PropertiesUtil.getProperty("signOffUrlStr"); ceBankReqUrlStr = PropertiesUtil.getProperty("ceBankReqUrlStr"); dataSignatureUrlStr = PropertiesUtil .getProperty("dataSignatureUrlStr"); } catch (Exception e) { logger.error("error:程序無法獲取properties中的配置信息"); } }
private static AccountBaseUtil bjBankBaseReq = null;
public static AccountBaseUtil getInstance() { if (bjBankBaseReq == null) { bjBankBaseReq = new AccountBaseUtil(); } return bjBankBaseReq; }
/** * 登錄交易 * * @param serialNo * 交易序列號(客戶端唯一標識) * @param reqTime * 客戶端請求時間 * @param userID * 用戶代碼 * @param userPWD * 用戶網銀密碼 * @return 返回 sessionID */ public String CebankUserLogon(BJBaseRequest req) { String v_desSession_id = null; URL url; HttpURLConnection urlConn; InputStream inStrm; String reqData; String retXml = new String(); // 獲取報文 reqData = this.createLoginXML(req); // 發起連接 try {
String new_reqData = new String(); // 簽名之後的數據 new_reqData = dataSignature(reqData); // 創建URL url = new URL(userLogonUrlStr + "?netType=3&reqData=" + new_reqData); // url = new URL(urlStr); logger.info(url.toString()); // 設置 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 使用了Get方法 urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setUseCaches(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("User-Agent", "API"); urlConn.setConnectTimeout(10000);
urlConn.connect(); // POST方法參數 /* * OutputStream os = urlConn.getOutputStream(); String param; param * = "netType=3&reqData=" + reqData; * * //param = URLEncoder.encode(param,"UTF-8"); * * //String paramater = "netType=3&reqData=" + reqData; * * //String paramater = reqData; //paramater = * dataSignature(paramater); //param = "netType=3&reqData=" + * paramater; * * //param = dataSignature("netType=3&reqData=" + reqData); * * os.write(param.getBytes()); */
// 獲取返回報文字符串 inStrm = urlConn.getInputStream();
} catch (Exception ex) { logger.error("連接服務器失敗"); return null; }
try(BufferedReader br = new BufferedReader(new InputStreamReader( inStrm, "gb2312"))) { // InputStreamReader ir = new InputStreamReader(inStrm,"gb2312"); String line = new String(); while (line != null) { retXml += line; line = br.readLine(); } logger.info(retXml); } catch (Exception ex) { //ex.printStackTrace(); logger.error("讀取服務器返回串錯誤 |{}",()->ex.toString());logger.debug("failed {}", ex); return null; } // 如果返回報文非空 if (!retXml.isEmpty()) v_desSession_id = this.parseLoginXML(retXml); return v_desSession_id; }
/** * 構建 登錄交易XML Document 報文 * * @param serialNo * @param reqTime * @param userID * @param userPWD * @return 登錄交易XML Document 報文 */ private String createLoginXML(BJBaseRequest req) { String retStr = null; Document reqData = null; try { DocumentBuilderFactory docFac = DocumentBuilderFactory .newInstance(); DocumentBuilder docB = docFac.newDocumentBuilder(); reqData = docB.newDocument(); // 設置 XML 文件版本為 1.0 reqData.setXmlVersion("1.0"); // 創建節點node Node n_root = reqData.createElement("BCCBEBankData"); Node n_opReq = reqData.createElement("opReq"); Node n_opName = reqData.createElement("opName"); n_opName.appendChild(reqData.createTextNode("CebankUserLogonOp")); // 交易名稱 Node n_serialNo = reqData.createElement("serialNo"); n_serialNo.appendChild(reqData.createTextNode(req.getSerialNo())); Node n_reqTime = reqData.createElement("reqTime"); n_reqTime.appendChild(reqData.createTextNode(req.getReqTime())); Node n_ReqParam = reqData.createElement("ReqParam"); Node n_userID = reqData.createElement("userID"); n_userID.appendChild(reqData.createTextNode(req.getUserID())); Node n_userPWD = reqData.createElement("userPWD"); n_userPWD.appendChild(reqData.createTextNode(req.getUserPWD()));
// 連接節點 reqData.appendChild(n_root);
n_opReq.appendChild(n_opName); n_opReq.appendChild(n_serialNo); n_opReq.appendChild(n_reqTime);
n_ReqParam.appendChild(n_userID); n_ReqParam.appendChild(n_userPWD);
n_root.appendChild(n_opReq); n_opReq.appendChild(n_ReqParam);
retStr = XmlModelUtil.XMLDoc2Str(reqData); retStr = retStr.replace(" standalone=\"no\"", "");
logger.debug(retStr);
} catch (Exception ex) { //ex.printStackTrace(); logger.error("創建 <登錄 XML 報文> 失敗 |{}",()->ex.toString());logger.debug("failed {}", ex); return null; } // 返回報文 return retStr; }
/** * 簽名 * * @param reqData * @return 返回是簽名後信息,簽名失敗返回null */ public static String dataSignature(String reqData) { URL url; HttpURLConnection urlConn; InputStream inStrm; String retHtml = new String(); String retData = null; // 發起連接 try { // 創建URL url = new URL(dataSignatureUrlStr); logger.debug(url.toString()); // 設置 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 使用了POST方法 urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("User-Agent", "API"); urlConn.setConnectTimeout(10000);
String contentLength = Integer.toString(reqData.length());
urlConn.setRequestProperty("Content-Length", contentLength); urlConn.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
// POST方法參數 OutputStream os = urlConn.getOutputStream(); String param = new String();
// param = "<body>" + reqData + "</body>"; param = reqData;
os.write(param.getBytes());
// 獲取返回報文字符串 inStrm = urlConn.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, "gb2312"))) {
String line = new String();while (line != null) {retHtml += line;line = br.readLine();}logger.info(retHtml);// 如果返回報文非空if (!retHtml.isEmpty()) {int sign_pos_b = retHtml.indexOf("<sign>");int sign_pos_e = retHtml.indexOf("</sign>");retData = retHtml.substring(sign_pos_b + 6, sign_pos_e);
retData = URLEncoder.encode(retData, System.getProperty("file.encoding"));}} } catch (Exception ex) { logger.error("dataSignature方法失敗"); return null;
} return retData; }
/** * 分析返回 XML 函數 分析 登錄 返回報文 * * @param v_retXml * @return 分析 登錄 返回報文 */ private String parseLoginXML(String v_retXml) { String retStr = new String(); String sessionID = null; String retXml = null; int indexOfsession; try { DocumentBuilderFactory docFac = DocumentBuilderFactory .newInstance(); DocumentBuilder docB = docFac.newDocumentBuilder(); indexOfsession = v_retXml.indexOf(‘|‘);
// 返回值 sessionID sessionID = v_retXml.substring(0, indexOfsession); retXml = v_retXml.substring(indexOfsession + 1);
InputStream is = new ByteArrayInputStream(retXml.getBytes());
Document retDoc = docB.parse(is); retDoc.normalize(); Node r_retCode = retDoc.getElementsByTagName("retCode").item(0) .getFirstChild(); retStr = r_retCode.getNodeValue(); if (retStr.equals(Integer.toString(0)) == false) { logger.debug(retStr); logger.debug(retDoc.getElementsByTagName("errMsg") .item(0).getFirstChild().getNodeValue()); } else { logger.debug(retDoc.getElementsByTagName("userName") .item(0).getFirstChild().getNodeValue()); logger.debug(retDoc.getElementsByTagName("corpName") .item(0).getFirstChild().getNodeValue()); logger.debug(retDoc.getElementsByTagName("lastLogon") .item(0).getFirstChild().getNodeValue()); } ; } catch (Exception ex) { //ex.printStackTrace(); logger.error("parseLoginXML Exception |{}"+retXml,()->ex.toString());logger.debug("failed {}", ex); }
if (sessionID.length() == 0) return null; else return sessionID; }
/** * 簽退交易 * * @param desSession_id * @return返回是否調用成功 0成功 -1失敗 */ public int CebankUserSignOff(String desSession_id) { URL url; HttpURLConnection urlConn; // 發起連接 try { // 創建URL url = new URL(signOffUrlStr + "?dse_sessionId=" + desSession_id); // url = new URL(urlStr); logger.info(url.toString()); // 設置 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 使用了Get方法 urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setUseCaches(true); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("User-Agent", "API"); urlConn.setConnectTimeout(10000); urlConn.connect(); /* * //POST方法參數 OutputStream os = urlConn.getOutputStream(); String * param = new String(); param = "dse_sessionId=" + desSession_id; * os.write(param.getBytes()); */ // 獲取返回報文字符串 urlConn.getInputStream(); } catch (Exception ex) { //ex.printStackTrace(); logger.error("簽退交易時,連接服務器失敗 |{}",()->ex.toString());logger.debug("failed {}", ex); return -1; } return 0; }
/** * 一般交易 * * @param opName * @param desSession_id * @param reqData * @return 銀行接口返回的 XML String */ public String CebankReq(String opName, String desSession_id, String reqData) { // String v_desSession_id = null; URL url; HttpURLConnection urlConn; InputStream inStrm; String retXml = null;
// 發起連接 try {
// 創建URL // url = new URL(urlStr + "?dse_sessionId=" + desSession_id + // "&opName=" + opName + "&reqData=" + reqData);
url = new URL(ceBankReqUrlStr + "?dse_sessionId=" + desSession_id); logger.info(url.toString()); // 設置 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 使用了post方法 urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setUseCaches(true); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("User-Agent", "API"); urlConn.setConnectTimeout(10000); // urlConn.connect();
// POST方法參數 OutputStream os = urlConn.getOutputStream(); String param = new String(); param = "opName=" + opName + "&reqData=" + reqData;
os.write(param.getBytes());
// 獲取返回報文字符串 inStrm = urlConn.getInputStream();
} catch (Exception ex) { //ex.printStackTrace(); logger.error("一般交易時,連接服務器失敗 |{}",()->ex.toString());logger.debug("failed {}", ex); return null; } try (BufferedReader br = new BufferedReader(new InputStreamReader( inStrm, "gb2312"))){ // InputStreamReader ir = new InputStreamReader(inStrm,"gb2312"); String line = new String(); while (line != null) { retXml += line; line = br.readLine(); } logger.info(retXml); } catch (Exception ex) { //ex.printStackTrace(); logger.error("一般交易時,讀取服務器返回信息錯誤 |{}",()->ex.toString());logger.debug("failed {}", ex); return null; } return retXml; }
}
redis 簡單使用