SpringBoot使用RedisTemplate整合Redis

  这两天写了写登录的逻辑, 从刚开始用cookie, 到用jwt token, 到单点登录, 随着系统的不断升级, 所用技术也在随之改变升级.  其中也遇到了一些坑, 尤其今天是redis 作为存储token的内存数据库.  之前用过

SpringBoot使用RedisTemplate整合Redis, 然后没写博客记录下, 结果今天再重新用的话, 还是要去看看资料什么的. 我想想还是记录一下比较好.  整理博客,写博客的事也要按计划进行

  Springboot整合Redis有两种方式,分别是Jedis和RedisTemplate,这两者有何区别?Jedis是Redis官方推荐的面向Java的操作Redis的客户端,而RedisTemplate是SpringDataRedis中对JedisApi的高度封装。其实在Springboot的官网上我们也能看到,官方现在推荐的是SpringDataRedis形式,相对于Jedis来说可以方便地更换Redis的Java客户端,其比Jedis多了自动管理连接池的特性,方便与其他Spring框架进行搭配使用如:SpringCache。不过jedis 方式能很清楚的看到其基本的工作方式,对Redis连接池的手动管理都能更清晰地体现出来。

  RedisTemplate官网文档地址:
  https://docs.spring.io/spring-data/redis/docs/2.0.3.RELEASE/reference/html/#redis:template

  对于redis 底层原理, 一些数据结构, 安装设计什么的, 我建议可以阅读平凡希大佬的博客, 他写的博客还是很牛逼的. https://www.cnblogs.com/xiaoxi/

 

springboot 与redis的整合

pom文件

  依赖如下:

    <dependencies>
<!-- redis -->
      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-redis</artifactId>
<!--         <version>2.0.9.RELEASE</version>-->
      </dependency>
      <dependency>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
<!--         <version>2.9.0</version>-->
      </dependency>
 </dependencies>

application.properties

  # Redis数据库索引(默认为0)
  spring.redis.database=0  
  # Redis服务器地址
  spring.redis.host=127.0.0.1
  # Redis服务器连接端口
  spring.redis.port=6379  
  # Redis服务器连接密码(默认为空)
  spring.redis.password=
  # 连接池最大连接数(使用负值表示没有限制)
  spring.redis.pool.max-active=8  
  # 连接池最大阻塞等待时间(使用负值表示没有限制)
  spring.redis.pool.max-wait=-1  
  # 连接池中的最大空闲连接
  spring.redis.pool.max-idle=8  
  # 连接池中的最小空闲连接
  spring.redis.pool.min-idle=0  
  # 连接超时时间(毫秒)
  spring.redis.timeout=0  

redisTemplate的配置

  新建一个redisConfig类,进行相关bean的配置:

package com.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author janti
 * reids 相关bean的配置
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 选择redis作为默认缓存工具
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        return rcm;
    }

    /**
     * retemplate相关配置
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}
  • spring-redis中使用了RedisTemplate来进行redis的操作,通过泛型的K和V设置键值对的对象类型。这里使用了string作为key的对象类型,值为Object。

  • 对于Object,spring-redis默认使用了jdk自带的序列化,不推荐使用默认了。所以使用了json的序列化方式

  • 对spring-redis对redis的五种数据类型也有支持

  • HashOperations:对hash类型的数据操作

  • ValueOperations:对redis字符串类型数据操作

  • ListOperations:对链表类型的数据操作

  • SetOperations:对无序集合类型的数据操作

  • ZSetOperations:对有序集合类型的数据操作

测试类

@RunWith(SpringRunner.class)

@SpringBootTest

public class RedisConfigTest {

    @Autowired private RedisTemplate redisTemplate;

    @Test public void test() throws Exception{

        ValueOperations<String,Object>  valueOperations = redisTemplate.opsForValue();

        valueOperations.set("shanghai","shanghai",20, TimeUnit.SECONDS); // 新增, 设置失效时间

        valueOperations.set("hebei","shijiazhuang2"); // 存在的话就是修改

        Object hebei = valueOperations.get("hebei");

          

 

    }

 

}

  像删除值, 删除主键这些操作可以查看官方文档或者百度搜索.  创建工具类什么的可以结合自己实际业务来写

注解缓存的使用

  • @Cacheable:在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;没有则调用方法并将方法返回值放进缓存。

  • @CachePut:将方法的返回值放到缓存中。

  • @CacheEvict:删除缓存中的数据。

猜你喜欢

转载自www.cnblogs.com/jingjiren/p/12704401.html
今日推荐