Spring Boot Caching with Redis - 反序列化问题
Posted
技术标签:
【中文标题】Spring Boot Caching with Redis - 反序列化问题【英文标题】:Spring Boot Caching with Redis - Deserialisation issue 【发布时间】:2018-09-25 19:36:42 【问题描述】:我尝试在我的 Spring Boot 项目中使用 Redis 实现缓存机制。我使用 mysql 作为我的数据库,并希望在内存数据库 (Redis) 中缓存一些数据,但是当我尝试检索数据时出现错误: Could not read 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));
应用程序.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>
最后是我从邮递员那里得到的完整错误:
"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】:@Cacheable(value = "mydata", key = "#id")
public MyObject findOneById(String id)
return myRepository.findOne(Integer.valueOf(id));
【讨论】:
您能否提供更多详细信息,说明您的答案如何帮助解决这个特定问题?谢谢。 效果很好。这是一个有用的链接。 getOne 只返回对象的实例,它是延迟加载的。 ***.com/questions/24482117/…以上是关于Spring Boot Caching with Redis - 反序列化问题的主要内容,如果未能解决你的问题,请参考以下文章
错误 java.sql.SQLException:在创建 Spring Boot 应用程序期间无法加载身份验证插件“caching_sha2_password”