1. 程式人生 > >使用shiro緩存用戶身份信息的時候報:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource

使用shiro緩存用戶身份信息的時候報:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource

解決問題 equals ola sim source ali ide string 問題

最近在使用shiro緩存用戶的身份信息的時候,報了simpleByteSource不能序列化,跟進源碼一看,原來這個類沒有實現序列化的接口,但是我在緩存身份信息的實現又要用到這個類,解決方法:重寫一個類,模仿著SimpleByteSoure這個類,寫個自己的類。並且實現序列化接口即可·。

 1 package com.dzf.shiro;
 2 
 3 import org.apache.shiro.codec.Base64;
 4 import org.apache.shiro.codec.CodecSupport;
 5 import org.apache.shiro.codec.Hex;
6 import org.apache.shiro.util.ByteSource; 7 8 import java.io.Serializable; 9 import java.util.Arrays; 10 11 /** 12 * <p> 13 * 為了解決redis序列化的問題,SimpleByteSource沒有實現序列化接口 14 * 在傳入simpleAuthenticationInfo()的時候,緩存用戶信息會出現序列化異常 15 * </p> 16 * @author dingzf 17 * @date 2018/3/7 18
* @time 21:54 19 */ 20 public class ShiroByteSource implements ByteSource, Serializable { 21 private static final long serialVersionUID = -6814382603612799610L; 22 private volatile byte[] bytes; 23 private String cachedHex; 24 private String cachedBase64; 25 26 public ShiroByteSource() {
27 28 } 29 30 public ShiroByteSource(String string) { 31 this.bytes = CodecSupport.toBytes(string); 32 } 33 34 public void setBytes(byte[] bytes) { 35 this.bytes = bytes; 36 } 37 38 @Override 39 public byte[] getBytes() { 40 return this.bytes; 41 } 42 43 @Override 44 public String toHex() { 45 if ( this.cachedHex == null ) { 46 this.cachedHex = Hex.encodeToString(getBytes()); 47 } 48 return this.cachedHex; 49 } 50 51 @Override 52 public String toBase64() { 53 if ( this.cachedBase64 == null ) { 54 this.cachedBase64 = Base64.encodeToString(getBytes()); 55 } 56 return this.cachedBase64; 57 } 58 59 @Override 60 public boolean isEmpty() { 61 return this.bytes == null || this.bytes.length == 0; 62 } 63 64 @Override 65 public String toString() { 66 return toBase64(); 67 } 68 69 @Override 70 public int hashCode() { 71 if (this.bytes == null || this.bytes.length == 0) { 72 return 0; 73 } 74 return Arrays.hashCode(this.bytes); 75 } 76 77 @Override 78 public boolean equals(Object o) { 79 if (o == this) { 80 return true; 81 } 82 if (o instanceof ByteSource) { 83 ByteSource bs = (ByteSource) o; 84 return Arrays.equals(getBytes(), bs.getBytes()); 85 } 86 return false; 87 } 88 89 public static ByteSource of(String string) { 90 return new ShiroByteSource(string); 91 } 92 }

在自己的實現的realm裏面調用如下:

1 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), new ShiroByteSource(user.getSalt()), getName());

以前的寫法是:

1 SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), new SimpleByteSource(user.getSalt()), getName());

然後就可以解決問題了。



使用shiro緩存用戶身份信息的時候報:java.io.NotSerializableException: org.apache.shiro.util.SimpleByteSource