zoukankan      html  css  js  c++  java
  • redis 简单使用

    /**
    * @title: PropertiesUtil.java
    * @package:util
    * @description:TODO
    * @author: lihuadong@lantrack.net
    * @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 lihuadong@lantrack.net
    * @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;    }
    }

  • 相关阅读:
    ffmpeg显示视频
    眼见为实(1):C++基本概念在编译器中的实现
    在Windows系统上实现轻量级的线程间及进程间消息队列
    Intellij IDEA 2017 debug断点调试技巧与总结详解篇
    redis 全局命令 查看所有的键,删除键,检查键是否存在,获取过期时间,键的数据结构类型
    java.security.InvalidKeyException: IOException : Short read of DER length
    RSA解密报错java.security.spec.InvalidKeySpecException的解决办法
    IntelliJ IDEA全局内容搜索和替换
    RSA加密/解密 Decryption error异常解决
    java rsa 解密报:javax.crypto.BadPaddingException: Decryption error
  • 原文地址:https://www.cnblogs.com/523823-wu/p/8659409.html
Copyright © 2011-2022 走看看