您的位置:首页 > 数据库 > Redis

SpringBoot (十一) :数据访问springboot整合redis高性能缓存_一点课堂(多岸学院)

2019-05-22 10:23 1006 查看

springboot整合redis缓存

  1. redis介绍

    Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。

  2. 整合redis

      pom文件

      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
    • 配置文件

      # REDIS (RedisProperties)
      # Redis数据库索引(默认为0)
      spring.redis.database=1
      # Redis服务器地址
      spring.redis.host=192.168.57.99
      # Redis服务器连接端口
      spring.redis.port=6379
      # Redis服务器连接密码(默认为空)
      spring.redis.password=123456
      # 连接超时时间(毫秒)
      spring.redis.timeout=30000
    • 测试

      @RunWith(SpringJUnit4ClassRunner.class)
      @SpringBootTest(classes = {HelloSpringboot.class})
      public class RedisTest {
      
      @Autowired
      private StringRedisTemplate stringRedisTemplate;
      
      @Autowired
      private RedisTemplate redisTemplate;
      
      @Test
      public void test2() throws Exception {
      stringRedisTemplate.opsForValue().set("site", "www.yidiankt.com");
      }
      
      @Test
      public void test() throws Exception {
      User user = new User();
      user.setAge(10);
      user.setBirth(new Date());
      user.setLastName("yidiankt");
      
      redisTemplate.opsForValue().set("author", user);
      
      //        User user2 = (User) redisTemplate.opsForValue().get("author");
      //        System.out.println(user2);
      }
    • stringRedisTemplate常用方法

      // HASH 是一个string类型的field和value的映射表,hash特别适合用于存储对象。
      stringRedisTemplate.opsForHash();
      
      // LIST 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)
      stringRedisTemplate.opsForList();
      
      // SET 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。
      stringRedisTemplate.opsForSet();
      
      // ZSET 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。
      stringRedisTemplate.opsForZSet();
    • 对象序列化格式问题

      默认JDK序列化

      \xAC\xED\x00\x05sr\x00!com.yidiankt.springboot.bean.User\xE2O\xFE\xAE\x87\xAB\x8F\xE6\x02\x00\x07L\x00\x03aget\x00\x13Ljava/lang/Integer;L\x00\x05birtht\x00\x10Ljava/util/Date;L\x00\x04bosst\x00\x13Ljava/lang/Boolean;L\x00\x03dogt\x00"Lcom/yidiankt/springboot/bean/Dog;L\x00\x08lastNamet\x00\x12Ljava/lang/String;L\x00\x05listst\x00\x10Ljava/util/List;L\x00\x04mapst\x00\x0FLjava/util/Map;xpsr\x00\x11java.lang.Integer\x12\xE2\xA0\xA4\xF7\x81\x878\x02\x00\x01I\x00\x05valuexr\x00\x10java.lang.Number\x86\xAC\x95\x1D\x0B\x94\xE0\x8B\x02\x00\x00xp\x00\x00\x00\x0Csr\x00\x0Ejava.util.Datehj\x81\x01KYt\x19\x03\x00\x00xpw\x08\x00\x00\x01j\xD3\x8E\.xppt\x00\x06nihaoapp
    • 修改JSON字符串

      [
      "com.yidiankt.springboot.bean.User",
      {
      "lastName": "yidiankt",
      "age": 12,
      "boss": null,
      "birth": [
      "java.util.Date",
      1558329539697
      ],
      "maps": null,
      "lists": null,
      "dog": null,
      "password": "123"
      }
      ]
  3. 添加json序列化配置

    @Configuration
    public class MyRedisConfig {
    
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    
    // 使用Jackson2JsonRedisSerialize 替换默认序列化
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    
    // 设置value的序列化规则和 key的序列化规则
    redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
    }
    }
  4. docker启动Redis配置(单机版)

    # 获取镜像
    docker pull  redis:3.2
    
    # 启动
    docker run -p 6379:6379 -v /opt/yidian/redis/data:/data -v /opt/yidian/redis/conf/redis.conf:/usr/local/etc/redis/redis.conf -d redis:3.2 redis-server /usr/local/etc/redis/redis.conf --appendonly yes
    
    # -p 6379:6379 : 将容器的6379端口映射到主机的6379端口
    # -v /opt/yidian/redis/data:/data : 将主机中当前目录下的data挂载到容器的/data
    # -d 后台运行容器,返回容器id
    # redis-server --appendonly yes : 在容器执行redis-server启动命令,并打开redis持久化配置
  5. SpringBoot使用spring cache缓存注解

      spring cache介绍概述

      Spring 3.1 引入了激动人心的基于凝视(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案,而是一个对缓存使用的抽象,通过在既有代码中加入少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

      Spring 的缓存技术还具备相当的灵活性。不仅能够使用 SpEL(Spring Expression Language)来定义缓存的 key 和各种 condition,还提供开箱即用的缓存暂时存储方案,也支持和主流的专业缓存。

    • 注解介绍

      @Cacheable 触发缓存入口
      #该注解表示所注解的方法支持缓存。当所注解的方法被调用时,Spring首先会根据参数从缓存中查找,如果没有则执行相应的方法,否则返回缓存的值;
      
      @CacheEvict 触发移除缓存
      #该注解表示所注解的方法执行后将清空相应缓存;
      
      @CacahePut 更新缓存
      #该注解表示所注解的方法在执行后能够将执行结果进行缓存,和@Cacheable注解不同的是,它所注解的方法每次都会执行,即使执行的结果在缓存中已经存在;而@Cacheable所注解的方法只有缓存中不存在时才会执行。
      
      @Caching 将多种缓存操作分组
      #当我们需要在一个方法上添加多个缓存注解(如:@CacheEvict和@CachePut),或者需要操作多个缓存时,可以使用该注解进行组合;
      
      @CacheConfig 类级别的缓存注解,允许共享缓存名称
      #该注解使用在类声明中,对该类中使用到缓存的方法统一进行配置,如,配置缓存的名称步骤
  6. 添加spring cache步骤

      config配置类,如下(修改JSON序列化)

      @Bean
      CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
      
      //初始化一个RedisCacheWriter
      RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
      //设置CacheManager的值序列化方式为json序列化
      RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
      RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
      .fromSerializer(jsonSerializer);
      RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
      .serializeValuesWith(pair);
      
      //设置默认超过期时间是30秒
      //defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
      //初始化RedisCacheManager
      RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
      
      return cacheManager;
      }
    • 在配置类中开启注解

      @EnableCaching
  7. redis解决分布式session共享问题

视频教程:http://www.yidiankt.com/course/subject/58


关注公众号-免费获取【JAVA核心知识点】!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: