StringSerializer.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package org.crazycake.shiro.serializer;
  2. import org.crazycake.shiro.exception.SerializationException;
  3. import java.io.UnsupportedEncodingException;
  4. public class StringSerializer implements RedisSerializer<String> {
  5. private static final String DEFAULT_CHARSET = "UTF-8";
  6. /**
  7. * Refer to https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html
  8. * UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, etc
  9. */
  10. private String charset = DEFAULT_CHARSET;
  11. @Override
  12. public byte[] serialize(String s) throws SerializationException {
  13. try {
  14. return (s == null ? null : s.getBytes(charset));
  15. } catch (UnsupportedEncodingException e) {
  16. throw new SerializationException("serialize error, string=" + s, e);
  17. }
  18. }
  19. @Override
  20. public String deserialize(byte[] bytes) throws SerializationException {
  21. try {
  22. return (bytes == null ? null : new String(bytes, charset));
  23. } catch (UnsupportedEncodingException e) {
  24. throw new SerializationException("deserialize error", e);
  25. }
  26. }
  27. public String getCharset() {
  28. return charset;
  29. }
  30. public void setCharset(String charset) {
  31. this.charset = charset;
  32. }
  33. }