使用Redis进行Spring Boot缓存 - 反序列化问题

时间:2018-04-16 06:36:33

标签: json spring-boot serialization redis deserialization

我尝试在Spring Boot项目中使用Redis实现缓存机制。我使用MySQL作为我的数据库,并希望将一些数据缓存在内存数据库(Redis)中,但当我尝试检索数据时出现错误:无法读取JSON ......

以下是我的代码的一部分:

端点:

@GetMapping(value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyObject> getDataById(@PathVariable(value = "id") Integer id)
{
    MyObject data = myService.findOneById(String.valueOf(id));
    return Optional.ofNullable(data)
            .map(mData -> new ResponseEntity<>(mData, HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

服务:

@Cacheable(value = "mydata", key = "#id")
public MyObject findOneById(String id) {
    return myRepository.getOne(Integer.valueOf(id));
}

application.yml

spring:
  application:
    name: Spring Boot Caching With Redis
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/redis?useUnicode=true&characterEncoding=utf8&useSSL=false
    name:
    username: root
    password: root
    hikari:
      data-source-properties:
      cachePrepStmts: true
      prepStmtCacheSize: 250
      prepStmtCacheSqlLimit: 2048
      useServerPrepStmts: true
  jpa:
    database-platform: org.hibernate.dialect.MySQLInnoDBDialect
    database: MYSQL
    show_sql: false
    properties:
      hibernate.cache.use_second_level_cache: false
      hibernate.cache.use_query_cache: false
      hibernate.generate_statistics: true
  jackson:
    serialization:
      write_dates_as_timestamps: false
  cache:
    type: redis

liquibase:
  change-log: classpath:liquibase/master.xml

server:
  port: 8080

debug: true

在我的主要课程中,我添加了 @EnableCaching 注释,并在我的 pom.xml 中添加了依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

最后,这是我从Postman得到的完整错误:

{
  "timestamp": "2018-04-16T06:34:27.331+0000",
  "status": 500,
  "error": "Internal Server Error",
  "exception": 
  "org.springframework.http.converter.HttpMessageNotWritableException",
  "message": "Could not write JSON: could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: 
      com.springboot.redis.domains.MyObject$$_jvstdc2_0[\"id\"])",
  "path": "/api/myObject/67"
}

1 个答案:

答案 0 :(得分:1)

@Cacheable(value = "mydata", key = "#id")
public MyObject findOneById(String id) {
    return myRepository.findOne(Integer.valueOf(id));
}