栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springBoot之 Redis 实例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/709326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号