首页 > 数据库 >spring boot下使用RedisTemplate操作redis存取对象

spring boot下使用RedisTemplate操作redis存取对象

时间:2022-09-22 22:25:40浏览次数:51  
标签:spring boot redis RedisTemplate new import 序列化 public redisTemplate

 

在spring boot环境下有个StringRedisTemplate对象,默认已经为我们配置好了,只需要自动注入过来就能用,但是使用它只能在Redis中存放字符串。具体操作如下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class Test {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    @Test
    public void test() throws Exception {
        stringRedisTemplate.opsForValue().set("aaa", "111");
        Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
 
    }
}

 


因为在StringRedisTemplate的构造器中,设置的序列化器是字符串,所以它只能存取字符串。构造器:

public StringRedisTemplate() {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        this.setKeySerializer(stringSerializer);
        this.setValueSerializer(stringSerializer);
        this.setHashKeySerializer(stringSerializer);
        this.setHashValueSerializer(stringSerializer);
    }


现在,如果我们想使用RedisTemplate存取对象,那我们只需要设置相应的序列化器就行了。操作如下:

package com.newegg.core.service.config;
 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
 
@Configuration
public class RedisConfig {
 
    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
 
        // 使用Jackson2JsonRedisSerialize 替换默认序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
 
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
 
        // 设置value的序列化规则和 key的序列化规则
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

 

 

接着我们来测试一下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class Test {
    @Autowired
    private RedisTemplate<Object,Object> template;
 
    @Test
    public void savereids() {
        User u=new User(1,"王伟",21);
        template.opsForValue().set(u.getId()+"",u);
        User result = (User) template.opsForValue().get(u.getId()+"");
        System.out.println(result.toString());
    }
 
    @Test
    public void saveHashReids(){
        for(int i=1;i<10;i++){
            User u=new User(i,"王伟",21);
            template.opsForHash().put("myCache",u.getId(),u);
        }
        ArrayList<User> list=template.opsForHash().values("myCache")
    }
}

 

标签:spring,boot,redis,RedisTemplate,new,import,序列化,public,redisTemplate
From: https://www.cnblogs.com/huoyz/p/16721041.html

相关文章

  • SpringBoot问题集合
    WhitelabelErrorPageThisapplicationhasnoexplicitmappingfor/error,soyouareseeingthisasafallback.MonJun2414:56:23CST2019Therewasanunex......
  • Spring annotation(jrebel.com)
    摘自https://www.jrebel.com/blog/spring-annotations-cheat-sheetAugust5,2021SpringAnnotationsCheatSheetJavaFrameworksDeveloperProductivityWe'veg......
  • 第一个spring项目
    第一个spring项目1、maven依赖导入<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.22</versi......
  • SpringBoot实现自定义注解
    SpringBoot支持我们开发者能够自定义注解,从而实现一些项目中遇到的特定问题,这个功能不知道用过的小伙伴们多不多,反正我是用得不多,但是使用之后就会发现,实在是太便捷了,配合......
  • Redis
    Redis持久化机制:怎么保证Redis挂掉之后再重启数据可以进行恢复?很多时候我们需要持久化数据也就是将内存中的数据写入到硬盘里面,大部分原因是为了之后重用数据(比如重启......
  • springboot中重写RedisTemplate
    1、引入jar包<!--引入redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>......
  • 如何优雅实现分布式锁-Redisson
    1、引入jar包<!--引入redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>......
  • Spring Boot项目——logback 动态获取yml文件配置参数
    背景在项目中,日志需要根据不同项目环境进行处理,比如记录日志级别,日志留存时间等。我们需要在不同的yml文件中设置变量,logback文件中动态获取参数,进行日志配置。方法......
  • Spring MVC框架:第十五章:多IOC容器整合
    多IOC容器整合SSM整合方式Spring、SpringMVC、MyBatisSpringMVC的核心Servlet会启动一个IOC容器,而ContextLoaderListener也会启动一个IOC容器。web.xml<?xmlversion......
  • springboot在线学习系统 在线教育系统 在线课程学习平台 在线课程推荐系统 在线课程平
    ......