SpringBoot学习系列(十四)------Redis整合

SpringBoot学习系列(十四)------Redis整合

前言

在前面的博文中,我们使用了SpringBoot默认的缓存来保存数据,但是在实际的工作中,我们经常使用如:memcache、ehcache、redis等缓存中间件,在本文中就介绍如何在SpringBoot中使用Redis作为缓存

正文

1. Redis的安装和使用

关于redis的安装和使用,网上已经有很多的文章或者视频,这里就不再赘述,我们直接在项目中使用即可,如果对redis的命令有不懂的,可以去www.redis.cn查看对应的文档.

2. SpringBoot操作redis

  • 在pom文件中引入redis的starter

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

    引入了redis的starter以后,cacheManager就变成了RedisCacheManager.

  • 在SpringBoot的配置文件中添加属性,指定redis的服务器IP

    spring.redis.host=redis主机IP地址

  • 使用stringRedisTemplate(key和value都是字符串)或者redisTemplate(key和valu都是对象)来操作redis缓存

    我们在引入了redis的starter后,SpringBoot就帮我们注入了对应的配置类:

    @Configuration
    @ConditionalOnClass({RedisOperations.class})
    @EnableConfigurationProperties({RedisProperties.class})
    @Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
    public class RedisAutoConfiguration {
        public 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;
        }
    }
    

    我们拿到对应的Template以后,就可以向redis中存取对应的数据了,我们知道,在redis中有以下五种数据类型:

    1. String 字符串
    2. List 列表
    3. Set 集合
    4. Hash 散列
    5. ZSet 有序集合

    而SpringBoot的Template里面也为我们封装了对应的方法来操作它们:

    1. stringRedisTemplate.opsForValue() [String(字符串)]
    2. stringRedisTemplate.opsForList() [List(列表)]
    3. stringRedisTemplate.opsForSet() [Set(集合)]
    4. stringRedisTemplate.opsForHash() [Hash(散列)]
    5. stringRedisTemplate.opsForZSet() [ZSet(有序集合)]

    我们只需要用着些方法就可以操作数据了.

  • 使用stringRedisTemplate操作数据:

    	@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");
    	}
    
  • 使用redisTemplate操作对象(对象在保存的时候需要实现序列化接口)

    	//测试保存对象
    	@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);
    	}
    
  • 我们除了使用redisTemplate来操作缓存,也可以使用上篇文章中提到的SpringBoot注解(@Cacheable、@CachePut等)来实现数据的缓存,具体的使用这里不再重复.

  • 我们在保存对象数据的时候,SpringBoot默认是使用JDK的序列化来保存数据的,这种方式保存的数据可视性很差,我们更希望用json的格式来保存数据,使用json保存数据有2中方式,第一,我们自己将数据转换为json字符串来保存.第二,改变redisTemplate的默认的序列化规则

    1. 首先创建一个redis的配置类,定义我们自己的redisTemplate:

      @Configuration
      public class MyRedisConfig {
      	
          /**
          *在创建这个redisTemplate的时候要传入要序列化的对象类型,在这里我们传入了User类
          */
          @Bean
          public RedisTemplate<Object, User> userRedisTemplate(
                  RedisConnectionFactory redisConnectionFactory)
                  throws UnknownHostException {
              RedisTemplate<Object, User> template = new RedisTemplate<Object, User>();
              template.setConnectionFactory(redisConnectionFactory);
              Jackson2JsonRedisSerializer<User> ser = new Jackson2JsonRedisSerializer<User>(User.class);
              template.setDefaultSerializer(ser);
              return template;
          }
      }
      
    2. 现在测试我们自定义的redisTemplate:

      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class Springboot01CacheApplicationTests {
      	@Autowired
      	RedisTemplate<Object, User> userRedisTemplate;
      	//测试保存对象
      	@Test
      	public void test02(){
      		User user = userMapper.getUserById(1);
      		//默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
      		userRedisTemplate.opsForValue().set("user-01",user);
              //现在我们可以使用redis的管理工具查看,可以发现,缓存的数据已经是json格式的了
      	}
      }
      
    3. 我们也可以直接自定义cacheManager来获得对应的缓存:

          @Bean
          public RedisCacheManager userCacheManager(RedisTemplate<Object, User> empRedisTemplate){
              RedisCacheManager cacheManager = new RedisCacheManager(userRedisTemplate);
              //key多了一个前缀
      
              //使用前缀,默认会将CacheName作为key的前缀
              cacheManager.setUsePrefix(true);
      
              return cacheManager;
          }
      

      在代码中获得对应的cache操作:

          @Autowired
          RedisCacheManager userCacheManager;
      
      	//使用缓存管理器得到对应的缓存进行API调用
          public User getUserById(Integer id){
              System.out.println("查询用户"+id);
              User user = userMapper.getUserById(id);
      
              //获取某个缓存
              Cache dept = userCacheManager.getCache("user");
              dept.put("user:1",department);
      
              return user;
          }
      
      
    4. 如果我们缓存的对象有多个,不仅仅是User,那么就要在配置类中增加对应的Template或者cacheManager.

    5. 需要注意的是,如果添加了多个缓存管理器,必须指定一个默认的cacheManager,不然会报错,使用注解@Primary来指定默认的cacheManager

  • 如果使用了注解的方式来操作缓存,我们在定义了Template或者cacheManager的时候,就可以在注解@Cacheable等注解中指定我们要使用的缓存处理器,这样就可以实现针对不用的类型缓存不同的数据或者解析.

总结

其实SpringBoot操作缓存还是很简单的,在项目的开放中,可以灵活的使用各种缓存的操作方式,不管是注解还是编码,正确的使用才是最重要的.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值