zoukankan      html  css  js  c++  java
  • Springboot2.0整合Redis(注解开发)

    一. pom.xm文件引入对应jar包

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

    二. application.yml引入redis服务端配置

      # redis相关配置
      redis:
        host: 192.168.80.3
        port: 6379
        database: 0
        timeout: 60s  # 数据库连接超时时间,springboot2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
        # 连接池配置,springboot2.0中直接使用jedis或者lettuce配置连接池
        jedis:
          pool:
            # 最大空闲连接数
            max-idle: 500
            # 最小空闲连接数
            min-idle: 50
            # 等待可用连接的最大时间,负数为不限制
            max-wait:  -1s
            # 最大活跃连接数,负数为不限制
            max-active: -1

      说明:Jedis和Lettuce的比较:

         Jedis :

          直连模式,在多个线程间共享一个 Jedis 实例时是线程不安全的,如果想要在多线程环境下使用 Jedis,需要使用连接池,

          每个线程都去拿自己的 Jedis 实例,当连接数量增多时,物理连接成本较高。

         Lettuce:

          连接是基于Netty的,连接实例可以在多个线程间共享,

          所以,一个多线程的应用可以使用同一个连接实例,而不用担心并发线程的数量。当然这个也是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

          通过异步的方式可以让我们更好的利用系统资源,而不用浪费线程等待网络或磁盘I/O。

    三.RedisConfig 配置RedisTemplate和CacheManage

    package com.luckydan.springboot.config;
    
    import java.time.Duration;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    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.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /**
    * @package: com.luckydan.springboot.config
    * @description: redis配置文件
    * @author: gl
    * @date: 2018年11月23日
    * @version: 1.0.0
     */
    @EnableCaching
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {
        
        @Bean(name="redisTemplate")
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
            RedisTemplate<Object, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(redisConnectionFactory);
     
            FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<Object>(Object.class);
         // value值的序列化采用fastJsonRedisSerializer
            template.setValueSerializer(serializer);
            template.setHashValueSerializer(serializer);
            // key的序列化采用StringRedisSerializer
            template.setKeySerializer(new StringRedisSerializer());
            template.setHashKeySerializer(new StringRedisSerializer());
     
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
        
        @Bean
        public CacheManager cacheManager(RedisConnectionFactory factory) {
            // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  
            // 设置缓存的默认过期时间,也是使用Duration设置
            config = config.entryTtl(Duration.ofMinutes(1))    
                    .disableCachingNullValues();     // 不缓存空值
    
            // 设置一个初始化的缓存空间set集合
            Set<String> cacheNames =  new HashSet<>();
            cacheNames.add("my-redis-cache1");
            cacheNames.add("my-redis-cache2");
    
            // 对每个缓存空间应用不同的配置
            Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
            configMap.put("my-redis-cache1", config);
            configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));
            
            // 使用自定义的缓存配置初始化一个cacheManager
            RedisCacheManager cacheManager = RedisCacheManager.builder(factory)     
                    .initialCacheNames(cacheNames)  // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                    .withInitialCacheConfigurations(configMap)
                    .build();
            return cacheManager;
        }
    }

    说明:在获取RedisTemplate过程中需要对key-value键值对分别进行序列化操作,可以使用Springboot自带的Jackson2JsonRedisSerializer进行序列化,也可以使用fastjson进行自定义序列化

    自定义序列化:略

    四.整合Redis需要使用的注解介绍:

      1.@Cacheable  可以标记在方法上,也可以标记在类上。当标记在方法上时表示该方法是支持缓存的,当标记在类上时则表示该类所有的方法都是支持缓存的。应用到读取数据的方法上,将先从缓存中读取该方法的返回值,如果没

         有再从DB获取数据,然后把数据添加到缓存中

          缓存是以键值对进行的,值就是方法的返回结果,至于键的话,Spring又支持两种策略,默认策略和自定义策略,需要注意的是当一个支持缓存的方法在对象内部被调用时是不会触发缓存功能的

       属性值:value,key,condition(参考注解@CacheEvcit的属性值),unless

    参数 解释 example
    unless            

    缓存条件:判断unless,如果返回false,则放入缓存(与Condition相反 )

     

    @CachePut

    (value="user",

    key="#root.method.name_+#userId" unless="#username eq han")

    condition

    缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存

    @Cacheable 将在执行方法之前( #result还拿不到返回值)判断condition,如果返回true,

    则查缓存;

    @CachePut  将在执行完方法后(#result就能拿到返回值了)判断condition,如果返回true,

    则放入缓存;

    @CacheEvcit  当beforeInvocation= false 表示在方法执行之后调用(#result就能拿到返

    回值了)且判断condition,如果返回true,则移除缓存。

    @CacheEvict

    (value="user",

    condition=”#userName.length()>2”)

      2.@CacheEvcit  应用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据

       属性值:value,key,condition,allentries,beforeInvocation

    参数 解释 example
    value

    缓存的名称,在 spring 配置文件中定义,

    必须指定至少一个

    例如:
    @Cacheable(value=”mycache”)
    @Cacheable(value={”cache1”,”cache2”}
    key

    缓存的 key,可以为空,如果指定要按照

    SpEL 表达式编写,如果不指定,则缺省

    按照方法的所有参数进行组合

    @CacheEvict

    (value=”user”,key=”#userName”)

    condition

    缓存的条件,可以为空,使用 SpEL 编写,

    返回 true 或者 false,只有为 true 才进行

    缓存

    @CacheEvict

    (value=”user”,condition=”#userName.length()>2”)

    allentries

    是否清空所有缓存内容,缺省为 false,

    如果指定为 true,则方法调用后将立即清

    空所有缓存

    @CachEvict(value=”user”,allEntries=true)
    beforeInvocation

    是否在方法执行前就清空,缺省为 false,

    如果指定为 true,则在方法还没有执行

    的时候就清空缓存,缺省情况下,如果

    方法执行抛出异常,则不会清空缓存

    @CachEvict

    (value=”user”,beforeInvocation=true)

      3.@CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存,

       具体步骤如下:Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。 

       与@Cacheable的区别:执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中

       属性值:value,key,condition,unless(参考注解@CacheEvcit的属性值),unless

         4. @CacheConfig  属于类级别的注解,当方法上的注解未注明value时,以@CacheConfig的value属性为准,当方法上注明value时,以方法上的注解value属性为准

      5. @Caching 可能组合多个Cache注解使用;比如用户新增成功后,我们要添加id–>user;username—>user;email—>user的缓存;此时就需要@Caching组合多个注解标签了

      ex:可以使用如下方式使用:

    @Caching(put = {
    @CachePut(value = "user", key = "#user.id"),
    @CachePut(value = "user", key = "#user.username"),
    @CachePut(value = "user", key = "#user.email")
    })
    public User save(User user) {}

      ex:也可以使用自定义注解的方式实现相应的功能 

    /**
    * 自定义注解
    */
    @Caching(put = {
    @CachePut(value = "user", key = "#user.id"),
    @CachePut(value = "user", key = "#user.username"),
    @CachePut(value = "user", key = "#user.email")
    })
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    public @interface UserSaveCache {
    }

    将自定义注解添加到指定的方法上:这种方法会使代码很干净(强力推荐)

    1 @UserSaveCache
    2 public User save(User user){}

      

        

  • 相关阅读:
    maven项目添加Gson的依赖后无法启动,报错BeanCreationException:Error creating bean with name 'gsonBuilder'
    'bool' object is not callable
    UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
    django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
    ForeignKey(unique=True) is usually better served by a OneToOneField.
    NameError: name 'reload' is not defined
    No module named 'django.core.urlresolvers'
    No module named 'ckeditor'
    [Docker] Leverage a Docker Maven plugin
    [Docker] Separate application image from database migration
  • 原文地址:https://www.cnblogs.com/maria-ld/p/10010219.html
Copyright © 2011-2022 走看看