十九、SpringBoot之整合redis实现缓存

Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。

1、引入redis的start:spring-boot-starter-data-redis

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

2、application.yml配置redis连接地址

spring.redis.host=172.16.40.148

3、使用RestTemplate操作redis

Redis常见的五大数据类型:String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
stringRedisTemplate:

  • 1. stringRedisTemplate.opsForValue();//操作String字符串
  • 2. stringRedisTemplate.opsForHash();//操作hash散列
  • 3. stringRedisTemplate.opsForList();//操作list列表
  • 4. stringRedisTemplate.opsForSet();//操作set集合
  • 5. stringRedisTemplate.opsForZSet();//操作有序set集合
    @Test
    public void test01(){
        //给redis中保存数据
        stringRedisTemplate.opsForValue().append("msg","hello");
        //根据key获取redis里的值
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.println(msg);
        //给redis中保存list
        stringRedisTemplate.opsForList().leftPush("mylist","1");
        stringRedisTemplate.opsForList().leftPush("mylist","2");
    }

4、使用RestTemplate操作redis

redisTemplate:

  • 1. redisTemplate.opsForValue();//操作String字符串
  • 2. redisTemplate.opsForHash();//操作hash散列
  • 3. redisTemplate.opsForList();//操作list列表
  • 4. redisTemplate.opsForSet();//操作set集合
  • 5. redisTemplate.opsForZSet();//操作有序set集合
    @Test
    public void test02(){
        Employee employee =   employeeMapper.getEmpById(1);
        //给redis中保存对象
        //1、默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
        employee序列化(Employee implements Serializable)
        redisTemplate.opsForValue().set("emp01",employee);
        //2、将数据以josn的方式保存
        //(1)自己将对象转化为josn
        //(2)redisTemplate默认序列化规则:改变默认序列化规则
        empRedisTemplate.opsForValue().set("emp-01",employee);
    }
@Configuration
public class MyRedisConfig {
    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
}

序列化原理:

RedisAutoConfiguration导入了两个组件
StringRedisTemplate:操作k-v字符串的
RedisTemplate:操作k-v对象的

RedisAutoConfiguration.java
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

        @Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<Object, Object> redisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		RedisTemplate<Object, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}

	@Bean
	@ConditionalOnMissingBean
	public StringRedisTemplate stringRedisTemplate(
			RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
		StringRedisTemplate template = new StringRedisTemplate();
		template.setConnectionFactory(redisConnectionFactory);
		return template;
	}
RedisTemplate.java
public void afterPropertiesSet() {
        super.afterPropertiesSet();
        boolean defaultUsed = false;
        if (this.defaultSerializer == null) {
            //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
            this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
        }

        if (this.enableDefaultSerializer) {
            if (this.keySerializer == null) {
                this.keySerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.valueSerializer == null) {
                this.valueSerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.hashKeySerializer == null) {
                this.hashKeySerializer = this.defaultSerializer;
                defaultUsed = true;
            }

            if (this.hashValueSerializer == null) {
                this.hashValueSerializer = this.defaultSerializer;
                defaultUsed = true;
            }
        }

        if (this.enableDefaultSerializer && defaultUsed) {
            Assert.notNull(this.defaultSerializer, "default serializer null and not all serializers initialized");
        }

        if (this.scriptExecutor == null) {
            this.scriptExecutor = new DefaultScriptExecutor(this);
        }

        this.initialized = true;
    }

5、自定义CacheManager

 原理:CacheManager(缓存管理器)创建 ==== Cache(缓存组件)来实现给缓存中存储数据
     1)、引入redis的starter,容器中保存的是RedisCacheManager
     2)、RedisCacheManager帮我们创建RedisCache来作为缓存组件,RedisCache通过操作redis缓存数据的
     3)、默认保存数据 K-V 都是Object;利用序列化保存;如何保存为json
     4)、自定义CacheManager:

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        redisSerializer.setObjectMapper(objectMapper);
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory).cacheDefaults(cacheConfiguration).build();
        return redisCacheManager;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值