springBoot之 Redis 实例

springBoot之 Redis 实例,第1张

springBoot之 Redis 实例 1. 环境搭建

连接上redis 服务

导入依赖


     org.springframework.boot
     spring-boot-starter-data-redis
 

在application.properties指定Redis服务器地址

#redis服务器主机地址
spring.redis.host=127.0.0.1

1.代码测试-给redis中保存数据

package com.atguigu.cache;

import com.atguigu.cache.bean.Employee;
import com.atguigu.cache.mapper.EmployeeMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class Springboot01CacheApplicationTests {
    @Autowired
    StringRedisTemplate stringRedisTemplate;  // *** 作k-v都是字符串的

    @Autowired
    RedisTemplate redisTemplate;  //k-v都是对象的

    
    @Test
    public void test01(){
        //给redis中保存数据
        stringRedisTemplate.opsForValue().append("msg","hello");
//		String msg = stringRedisTemplate.opsForValue().get("msg");
//		System.out.println(msg);

//		stringRedisTemplate.opsForList().leftPush("mylist","1");
//		stringRedisTemplate.opsForList().leftPush("mylist","2");
    }

}

2.测试保存对象

    @Test
    public void test02(){
        Employee empById = employeeMapper.getEmpById(1);
        //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
        redisTemplate.opsForValue().set("emp-01",empById);
        //1、将数据以json的方式保存
        //(1)自己将对象转为json
        //(2)redisTemplate默认的序列化规则;改变默认的序列化规则;
//        empRedisTemplate.opsForValue().set("emp-01",empById);
    }

注:必须要申明可序列化

redis 保存的结果如下:使用jdk序列化机制,序列化后的数据保存到redis中

2.改变默认的序列化规则

redisTemplate默认的序列化规则;改变默认的序列化规则

重实现RedisAutoConfiguration 写为自己的规则json格式展示

template.setDefaultSerializer(ser);


实现代码:

package com.atguigu.cache.config;


import com.atguigu.cache.bean.Employee;
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 java.net.UnknownHostException;

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate empRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer user = new Jackson2JsonRedisSerializer(Employee.class);
        template.setDefaultSerializer(user);
        return template;
    }
}


测试代码


如图数据已被序列化成为JSON格式的了

3. 原理解析

只要引入redis 配置:


     org.springframework.boot
     spring-boot-starter-data-redis
 

缓存就开启redis:
引入redis的starter,容器中保存的是 RedisCacheManager;

 * 		原理:CacheManager===Cache 缓存组件来实际给缓存中存取数据
 *		1)、引入redis的starter,容器中保存的是 RedisCacheManager;
 *		2)、RedisCacheManager 帮我们创建 RedisCache 来作为缓存组件;RedisCache通过 *** 作redis缓存数据的
 *		3)、默认保存数据 k-v 都是Object;利用序列化保存;如何保存为json
 *   			1、引入了redis的starter,cacheManager变为 RedisCacheManager;
 *   			2、默认创建的 RedisCacheManager  *** 作redis的时候使用的是 RedisTemplate
 *   			3、RedisTemplate 是 默认使用jdk的序列化机制
 *      4)、自定义CacheManager;

启动查询数据库还不是json格式的

视频中使用的是spring-boot 2(1.5.12)以下版本,我的是spring-boot 2以上的版本(2.3.7)

    spring-boot 2(1.5.12)以下版本源码


MyRedisConfig

    @Bean
    public RedisTemplate deptRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer(Department.class);
        template.setDefaultSerializer(ser);
        return template;
    }
    spring-boot 2以上的版本(2.3.7) 源码


MyRedisConfig

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
                .disableCachingNullValues()
                .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }

经过测试是OK的,测试URL:http://localhost:8080/emp/1

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5707867.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存