Consider defining a bean of type 'org.springframework.data.redis.core.HashOperations' 的解决

编程知识 更新时间:2023-05-02 05:34:40

在spring boot整合redis时,本以为springboot已经实现了对redis的完美结合。只需要一个@Autowired就可以使用RedisTemplate模板了,结果项目启动出现了下面的惊喜。。。

很明显让我们指明RedisTemplate在项目中的配置。果然,好记性不如烂笔头,突然想起来在之前的项目中已经使用过redis,其中就有这部分内容,但自己负责的不是这个模块而已,很是尴尬。。。

所以我找到RedisTemplate注册bean.

package com.dsx.redis.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/***
 * 
* @ClassName: RedisConfig  
* @Description: redis配置类
* @author 曰业而安  
* @date 2020年3月23日  
*
 */
 
@Configuration
public class RedisConfig {
    
	@Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        // key采用String的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // value序列化方式采用jackson
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
	
}

至此,RedisTemplate就可以使用了,还有切记在分布式中我们对redis的序列化要采用一致的方式呦。不然会出现bug。还有很多小伙伴使用的是StringRedisTemplate,它是RedisTemplate的子类。

StringRedisTemplate只能存储String类型的,即StringRedisTemplate<String,String>。用这一个模板是不需要将我们的对象实现序列化的,因为我们在存储对象之前,必须要将对象转Json才行,不然会存储不进去的。值得我们注意的是:两个template千万不要操作相同的Key。它们对同一个key的操作会相互影响的。

以上就是对此次bug的小结,如有不同见解,欢迎留言呦。。。

更多推荐

Consider defining a bean of type 'org.springframework.data.redis.core.HashO

本文发布于:2023-04-26 07:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/05d089e614194fe0769799a340bcc136.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:type   org   defining   bean   springframework

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 104684文章数
  • 26218阅读数
  • 0评论数