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));
    }
   
}

 

 

转载于:https://www.cnblogs.com/foreverYoungCoder/p/9166416.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值