• Base64工具类并发问题!


    为减少对象创建次数,一般会做如下编码:

    public class EncodeUtils {
    	private static BASE64Encoder encoder;
    	private static BASE64Decoder decoder;
    	
    	public static boolean isNULLorEmpty(String str){
    	  if(str==null||str.trim().equals(""))
    		return true;
    	  else
    		return false;
    	}
    	
    	/**
    	 * 
    	 * 方法名称:encode
    	 * 功能说明:字符串数据进行BASE64加密
    	 * @param str
    	 * @return
    	 */
    	public static String encode(String str){
    		if(encoder == null) encoder = new BASE64Encoder();
    		return encoder.encode(str.getBytes());
    	}
    	
    	/**
    	 * 
    	 * 方法名称:decode
    	 * 功能说明:字符串数据进行BASE64解密
    	 * @param str
    	 * @return
    	 * @throws IOException
    	 */
    	public static String decode(String str) throws IOException {
    		if(decoder==null) decoder = new BASE64Decoder();
    		return new String(decoder.decodeBuffer(str));
    	}
       
    }
    

      这样写,看似没问题,但是在高并发下会存在问题,同一字符串解码出来的信息不一致,BASE64Encoder、BASE64Decoder 不是线程安全的类

    所以可以按如下修改,有两种方案,一种是每次都重新创建个对象,另外一种是替换jra包,不用jre带的,用org.apache.commons.codec下的base64,这个是线程安全的类

    修改如下:

    	/**
    	 * 
    	 * 方法名称:decode
    	 * 功能说明:字符串数据进行BASE64解密
    	 * @param str
    	 * @return
    	 * @throws IOException
    	 */
    	public static String decode(String str) throws IOException {
    		return new String(new BASE64Decoder().decodeBuffer(str));
    	}
    

      或者换jar包

    public class EncodeUtils {
    
        private static Base64 base64 = new Base64();
        
        
    /**
         * 
         * 方法名称:decode
         * 功能说明:字符串数据进行BASE64解密
         * @param str
         * @return
         * @throws IOException
         */
        public static String decode(String str) throws IOException {
            return new String (base64.decode(str));
        }
       
    }
    
    
  • 相关阅读:
    多进程编程
    Python 的下载安装
    cnBlogs windows LIves Writes 安装
    第四章网页文字编排设计
    第三章网页图形图像设计
    第二章网页创意设计思维和方法
    1.3-1.4网页设计的定位和流程
    1.2网页设计的构成要素和特性
    网页编辑常用快捷方式+学习技巧+网站开发流程
    css选择器2——伪类选择器
  • 原文地址:https://www.cnblogs.com/foreverYoungCoder/p/9166416.html
Copyright © 2020-2023  润新知