【SpringBoot】最通俗易懂缓存机制学习(三)--Springboot整合Redis及序列化机制

注:本文章基于尚硅谷Springboot高级特性相关视频及资料进行编写,代码简单,较容易理解,若有问题或者源码资料获取可以在评论区留言或者联系作者!


在这里插入图片描述

前言

        在之前的学习中,我们已经完成了基本的SpringBoot默认缓存管理的体验,了解了SpringBoot缓存常用的注释和原理,接下来我们将对其进行redis进行整合,将Redis作为缓存组件实现缓存管理;

         首先我们需要了解,在Springboot中,数据的管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.springframework.cache.CacheManager缓存管理接口。如果程序中没有定义类型为cacheamanager的Bean组件或者是名为caheResolver的CacheResolver缓存解析器,SpringBoot将尝试选择启用按照指定顺序的缓存组件,这里对于下面的自定义RedisTemplate和RedisCacheManager尤为重要;



基于注解的Redis缓存实现

(1)首先添加redis的依赖启动器;

<!--        引入redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

(2)进行redis服务配置,使用Redis这种第三方的缓存组件进行缓存管理时候,缓存数据并不是像SpringBoot那样存储在内存中,而是要预先搭载类似Redis服务的数据仓库进行缓存,所以要在下面的配置文件中对redis进行配置;

spring.redis.host={你的redis服务地址}
spring.redis.port=6379{一般都是6379端口,如果你自己设置了就按你自己设置的来}
spring.redis.password={你的redis访问密码,不填则为空}

(3)进行实体类的序列化,,在对实体类对象进行缓存存储时必须实现序列化(一些基本的数据类型不需要序列化,因为内部已经默认实现了序列化 接口),否则会出现缓存异常,导致程序无法运行,接下来我们需要对进行缓存存储的Employee实现序列化接口,实现序列化;

public class Employee implements Serializable {
’省略代码‘}


(4)运行之前的环境,进行查询操作,会发现,能够正常查询数据,且打开RedisdsktopManager的管理工具,会发现的确将数据存入了缓存组件中,但是一串HEX格式的数据,这是因为这里序列化是采用默认的JDK默认序列化机制,这里我们会在后面进行自定义的数据序列化的格式;

控制台在后续的查询中不输出
在这里插入图片描述



基于API的Redis的缓存实现

前面我们使用了基于注解的Redis缓存实现,下面来看一中开发中更为常用的方式——基于API的Redis的实现,


首先需要先了解一下RedisTemplate,它是Spring Data Redis提供的直接进行redis操作的Java API,可以直接注入使用;
RedisTemplate可以操作

下面对API接口的使用作一个简单的示例; (1)编写Test文件;,这里将使用StringTemplate进行简单说的字符串数据的插入和查询操作

 void test01(){
        //给redis中保存一个数据
       stringRedisTemplate.opsForValue().append("msg","你好");
        //取出redis中的数据
      String hello = stringRedisTemplate.opsForValue().get("hello");
       System.out.println(hello);
    }


执行test文件,可以看见网redis数据仓库中插入了一个msg:”你好“ 的数据 然后控制台页面也输出了key为hello的value值

在这里插入图片描述

在这里插入图片描述



自定义Redis缓存序列化机制

在前面我们看到了当存入普通数据时可以正常进行存储,但当存储类时需要经过序列化才可以进行存储,而且使用默认的jdk序列化机制的时候并不能完全存储为我们想要的结果,接下来我们就将自定义Redis的缓存机制,得到我们想要的结果;

自定义RedisTemplate序列化机制

(1)创建一个MyConfig类进行配置

@Configuration
public class MyRedisConfig {
   @Bean
    public RedisTemplate<Object, Object> empredisTemplate(RedisConnectionFactory redisConnectionFactory) {
       RedisTemplate<Object, Object> template = new RedisTemplate();
       template.setConnectionFactory(redisConnectionFactory);
       Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<Object>(Object.class);
       template.setDefaultSerializer(ser);
      return template;
 }

(2)创建测试类,使用API方式存入一个对象:

 //测试保存对象
    @Test
    void test02(){
        //这里需要进行改变序列化规则
        Employee empbyId = employeeMapper.getEmpbyId(1);
        employeeRedisTemplate.opsForValue().set("emp-01",empbyId);
        Employee employee = employeeRedisTemplate.opsForValue().get("emp-01");
        System.out.println(employee);

    }

(3)执行测试类,会发现redis数据仓库中能正常存储,且为我们想要的数据;
在这里插入图片描述
在这里插入图片描述

自定义RedisCacheManager

(1)在之前的配置类中定制自定义名为cacheManager的组件,实例代码如下:

@Bean(name = "cacheManager")
@Primary
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(10)) //设置过期时间
                .disableCachingNullValues()   //禁止缓存null对象
               *//* .computePrefixWith(cacheName -> "yourAppName".concat(":").concat(cacheName).concat(":"))*//* //此处定义了cache key的前缀,避免公司不同项目之间的key名称冲突
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) //定义了key和value的序列化协议,同时hash key和hash value也被定义
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(Object.class)));

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }

(2)由于最后运行结果一样,所以这里将不再叙述,可以自行演示;

至此Springboot缓存机制学习完毕!!!!!!!



总结

我们需要了解:

  1. Singboot默认缓存
    - Simple:默认使用内存中的ConcurrentHashMap进行缓存存储
    - 相关注解的使用
  2. 使用Redis缓存
    - Redis:存储在Redis数据仓库
    - 基于注解的Redis缓存实现
    - 基于API注解的缓存实现(优先使用)
    - 自定义序列化机制
    (1)自定义RedisTemplate
    (2)自定义RedisCacheManager(注意Springboot版本)

在这里插入图片描述

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
Spring Boot中使用Spring Data Redis进行Redis Geo操作,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.6.0</version> </dependency> ``` 然后在application.properties文件中配置Redis相关信息: ```properties # Redis spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 接下来,我们需要创建一个RedisGeoService来进行Geo操作: ```java @Service public class RedisGeoService { private final RedisTemplate<String, String> redisTemplate; public RedisGeoService(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 添加地理位置信息 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param member 成员 * @return Long */ public Long add(String key, double longitude, double latitude, String member) { Point point = new Point(longitude, latitude); return redisTemplate.opsForGeo().add(key, point, member); } /** * 获取两个地理位置的距离 * * @param key 键 * @param member1 成员1 * @param member2 成员2 * @param unit 距离单位 * @return Distance */ public Distance distance(String key, String member1, String member2, Metric unit) { return redisTemplate.opsForGeo().distance(key, member1, member2, unit); } /** * 获取指定成员的地理位置 * * @param key 键 * @param members 成员 * @return List<Point> */ public List<Point> position(String key, String... members) { return redisTemplate.opsForGeo().position(key, members); } /** * 获取指定地理位置附近的成员 * * @param key 键 * @param longitude 经度 * @param latitude 纬度 * @param radius 半径 * @param unit 距离单位 * @return GeoResults<GeoLocation<String>> */ public GeoResults<GeoLocation<String>> nearBy(String key, double longitude, double latitude, double radius, Metric unit) { Circle circle = new Circle(longitude, latitude, new Distance(radius, unit)); GeoRadiusCommandArgs args = GeoRadiusCommandArgs.newGeoRadiusArgs().sortAscending(); return redisTemplate.opsForGeo().radius(key, circle, args); } } ``` 上述代码中,我们使用了RedisTemplate来进行Redis操作。RedisTemplate是Spring Data Redis提供的核心组件,用于执行Redis命令。 在RedisGeoService中,我们定义了四个方法来进行Geo操作: - add方法:添加地理位置信息。 - distance方法:获取两个地理位置的距离。 - position方法:获取指定成员的地理位置。 - nearBy方法:获取指定地理位置附近的成员。 使用Spring Boot和Spring Data Redis进行Geo操作非常方便,只需要定义一个RedisGeoService,并注入RedisTemplate即可。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PoJo123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值