私は使っている Spring Data Redis
とともに Spring Boot 2.0
例。この例では、顧客データと学生データを一緒に保存しようとしています。ここでデータモデリングがどのように行われるかはよくわかりませんが、Mongo DB(純粋な非リレーショナル)と同じであると想定しています。
誰かが以下のエラーを手伝ってくれませんか?明らかなように、データを見るにはある程度の変換が期待されています。
エラー:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [com.javasampleapproach.redis.model.Customer] to type [Java.lang.String]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.Java:321)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.Java:194)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.Java:174)
at org.springframework.data.redis.serializer.GenericToStringSerializer$Converter.convert(GenericToStringSerializer.Java:120)
at org.springframework.data.redis.serializer.GenericToStringSerializer.serialize(GenericToStringSerializer.Java:88)
at org.springframework.data.redis.core.AbstractOperations.rawHashValue(AbstractOperations.Java:184)
at org.springframework.data.redis.core.DefaultHashOperations.put(DefaultHashOperations.Java:175)
at com.javasampleapproach.redis.repository.CustomerRepositoryImpl.save(CustomerRepositoryImpl.Java:33)
at com.javasampleapproach.redis.repository.CustomerRepositoryImpl$$FastClassBySpringCGLIB$$88e26a2c.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.Java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.Java:746)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.Java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.Java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.Java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.Java:688)
at com.javasampleapproach.redis.repository.CustomerRepositoryImpl$$EnhancerBySpringCGLIB$$7d20fd4e.save(<generated>)
at com.javasampleapproach.controller.WebController.save(WebController.Java:31)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at Java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.Java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.Java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.Java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.Java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.Java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.Java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.Java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.Java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.Java:974)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.Java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.Java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.Java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.Java:742)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:231)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.Apache.Tomcat.websocket.server.WsFilter.doFilter(WsFilter.Java:52)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.Java:158)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.Java:126)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.Java:111)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.Java:90)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.Java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.Java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.Java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.Java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.Java:107)
at org.Apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.Java:193)
at org.Apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.Java:166)
at org.Apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.Java:198)
at org.Apache.catalina.core.StandardContextValve.invoke(StandardContextValve.Java:96)
at org.Apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.Java:496)
at org.Apache.catalina.core.StandardHostValve.invoke(StandardHostValve.Java:140)
at org.Apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.Java:81)
at org.Apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.Java:87)
at org.Apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.Java:342)
at org.Apache.coyote.http11.Http11Processor.service(Http11Processor.Java:803)
at org.Apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.Java:66)
at org.Apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.Java:790)
at org.Apache.Tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.Java:1468)
at org.Apache.Tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.Java:49)
at Java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at Java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.Apache.Tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.Java:61)
at Java.lang.Thread.run(Unknown Source)
RedisConfig.Java
@Configuration
@ComponentScan("com.javasampleapproach.*")
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(){
final RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class));
template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
return template;
}
}
Controller.Java
@RequestMapping("/save")
public String save() {
List<Student> students = new ArrayList<>();
Student student = Student.builder().firstName("John").build();
students.add(student);
customerRepository.save(Customer.builder().id(1).firstName("Jack").lastName("Smith").students(students).build());
return "Done";
}
CustomerRepositoryImpl.Java
@Repository
public class CustomerRepositoryImpl implements CustomerRepository {
private static final String KEY = "Customer";
private RedisTemplate<String, Object> redisTemplate;
private HashOperations<String, Long, Customer> hashOperations;
@Autowired
public CustomerRepositoryImpl(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@PostConstruct
private void init() {
hashOperations = redisTemplate.opsForHash();
}
@Override
public void save(Customer customer) {
hashOperations.put(KEY, customer.getId(), customer);
}
@Override
public Customer find(Long id) {
return hashOperations.get(KEY, id);
}
@Override
public Map<Long, Customer> findAll() {
return hashOperations.entries(KEY);
}
@Override
public void update(Customer customer) {
hashOperations.put(KEY, customer.getId(), customer);
}
@Override
public void delete(Long id) {
hashOperations.delete(KEY, id);
}
}
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<Java.version>1.8</Java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
オブジェクトを永続化する前に、シリアライザーを使用する必要があります。 Spring Data Redis docs のこの部分を参照してください:
データは、Redis内のさまざまなデータ構造を使用して保存できます。 Jackson2JsonRedisSerializerは、オブジェクトをJSON形式に変換できます。理想的には、JSONはプレーンキーを使用して値として保存できます。 Redisハッシュを使用すると、構造化オブジェクトのより高度なマッピングを実現できます。 Spring Data Redisは、データをハッシュにマッピングするためのさまざまな戦略を提供します(ユースケースに応じて)。
- HashOperationsとシリアライザーを使用した直接マッピング
- Redisリポジトリの使用
- HashMapperとHashOperationsの使用
編集:
GenericToStringSerializer
Bean定義のRedisTemplate
をJdkSerializationRedisSerializer
(デフォルトのシリアライザー)またはJackson2JsonRedisSerializer
またはGenericJackson2JsonRedisSerializer
に置き換えて、JSON形式でシリアル化します。
@Gustavo Passiniからのガイダンスに従い、 https://www.programcreek.com/Java-api-examples/index.php?api=org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer から参照してください。 =。
これが
@Bean
public RedisTemplate<String, Object> redisTemplate(){
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
final RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
return template;
}