Spring Session Redis 序列化器 SerializationException

joe*_*lux 5 spring tomcat redis spring-session

为了尝试为现有应用程序外部化 tomcat 会话,我正在尝试 Spring Session Redis 解决方案。按照以下步骤在 pom.xml 中包含必要的依赖项后,如下所示:

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>1.2.1.RELEASE</version>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

在 web.xml 中添加 springSessionRepositoryFilter,如下所示:

<filter>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSessionRepositoryFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Run Code Online (Sandbox Code Playgroud)

并在 Spring XML 配置中添加以下内容

<bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"/>

<context:property-placeholder location="classpath:application.properties"/>

<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:port="${spring.redis.port}"/>
Run Code Online (Sandbox Code Playgroud)

并构建并部署到 tomcat,这是我收到的错误:

org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.io.NotSerializableException: com.sun.jersey.client.apache.ApacheHttpClient
Run Code Online (Sandbox Code Playgroud)

任何建议或帮助将不胜感激。谢谢 !!还附上我的 pom.xml 条目: pom.xml 条目

Sun*_*amy 1

从您的例外情况来看, com.sun.jersey.client.apache.ApacheHttpClient 不可序列化,因为它没有实现 java.io.Serializable。

您需要以其他方式序列化 ApacheHttpClient,因为它是第 3 方库。

您可以使用Jackson 库org.codehaus.jackson.map.ObjectMapper来实现此目的。

请参考这个例子

您还可以尝试随 HttpClient 附带的 SerializedEntity 类。

httpost.setEntity(new SerializableEntity(mySerializableObj, false));
Run Code Online (Sandbox Code Playgroud)

以下是使类可序列化的一般方法。

  • 如果该类是您的,请将其设为可序列化(这不是的情况)
  • 如果该类是3rd party,但您不需要以序列化形式使用它,则将该字段标记为瞬态
  • 如果您需要它的数据并且它是第三方的,请考虑其他序列化方式,例如JSON、XML、BSON、MessagePack等。您可以在不修改其定义的情况下序列化第三方对象。