• springboot整合Redis


    springboot整合Redis

    导入redis的依赖

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

    配置application.yml

    spring:
      redis:
        database: 0
        host: 192.168.241.132
        port: 6379
        password: 123456
        jedis:
          pool:
            max-active: 100
            max-idle: 3
            max-wait: -1
            min-idle: 0
        timeout: 1000

    创建一个配置类RedisConfig

    继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承

    package com.liuwenwu.springboot02.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.cache.interceptor.KeyGenerator;
    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.core.StringRedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import java.lang.reflect.Method;
    import java.time.Duration;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Map;
    import java.util.Set;
    
    /**
     * redis配置类
     **/
    @Configuration
    @EnableCaching//开启注解式缓存
    //继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
    public class RedisConfig extends CachingConfigurerSupport {
    
        /**
         * 生成key的策略 根据类名+方法名+所有参数的值生成唯一的一个key
         *
         * @return
         */
        @Bean
        @Override
        public KeyGenerator keyGenerator() {
            return new KeyGenerator() {
                @Override
                public Object generate(Object target, Method method, Object... params) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(target.getClass().getName());
                    sb.append(method.getName());
                    for (Object obj : params) {
                        sb.append(obj.toString());
                    }
                    return sb.toString();
                }
            };
        }
    
        /**
         * 管理缓存
         *
         * @param redisConnectionFactory
         * @return
         */
        @Bean
        public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
            //通过Spring提供的RedisCacheConfiguration类,构造一个自己的redis配置类,从该配置类中可以设置一些初始化的缓存命名空间
            // 及对应的默认过期时间等属性,再利用RedisCacheManager中的builder.build()的方式生成cacheManager:
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();  // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
            config = config.entryTtl(Duration.ofMinutes(1))     // 设置缓存的默认过期时间,也是使用Duration设置
                    .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)));
    
            RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)     // 使用自定义的缓存配置初始化一个cacheManager
                    .initialCacheNames(cacheNames)  // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                    .withInitialCacheConfigurations(configMap)
                    .build();
            return cacheManager;
        }
    
        @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
            RedisTemplate<Object, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(connectionFactory);
    
            //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
            Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
    
            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            serializer.setObjectMapper(mapper);
    
            template.setValueSerializer(serializer);
            //使用StringRedisSerializer来序列化和反序列化redis的key值
            template.setKeySerializer(new StringRedisSerializer());
            template.afterPropertiesSet();
            return template;
        }
    
        @Bean
        public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
            StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
            stringRedisTemplate.setConnectionFactory(factory);
            return stringRedisTemplate;
        }
    
    }

    SpringBoot整合redis及其注解式开发

    常用缓存注解

    @Cacheable:作用是主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 

    主要参数说明: 

      1) value : 

      缓存的名称,在 spring 配置文件中定义,必须指定至少一个,

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

      2) key :缓存的 key,可以为空,

      如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合,

      例如:@Cacheable(value=”testcache”,key=”#userName”)。 

      3) condition :缓存的条件,可以为空,

    案例如下:

    service层

    package com.liuwenwu.springboot02.service;
    
    import com.liuwenwu.springboot02.entity.Book;
    import com.liuwenwu.springboot02.util.PageBean;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.Cacheable;
    
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author LWW
     * @site www.lww.com
     * @company
     * @create 2019-11-09 11:04
     */
    public interface BookService {
    
        int deleteByPrimaryKey(Integer bid);
    
        @Cacheable(value = "my-redis-cache1",key = "'book'+#bid",condition = "#bid<20")
        Book selectByPrimaryKey(Integer bid);
    
        @CacheEvict(value = "my-redis-cache1",allEntries = true)
        void clear();
    
    
        List<Map> bookPager(Map map, PageBean pageBean);
    
    }

    BookServiceImpl

    package com.liuwenwu.springboot02.service.impl;
    
    import com.liuwenwu.springboot02.entity.Book;
    import com.liuwenwu.springboot02.mapper.BookMapper;
    import com.liuwenwu.springboot02.service.BookService;
    import com.liuwenwu.springboot02.util.PageBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author LWW
     * @site www.lww.com
     * @company
     * @create 2019-11-09 11:05
     */
    @Service
    public class BookServiceImpl implements BookService {
    
        @Autowired
        private BookMapper bookMapper;
    
        @Override
        public int deleteByPrimaryKey(Integer bid) {
            return bookMapper.deleteByPrimaryKey(bid);
        }
    
        @Override
        public Book selectByPrimaryKey(Integer bid) {
            return bookMapper.selectByPrimaryKey(bid);
        }
    
        @Override
        public void clear() {
            System.out.println("此处不需要代码");
        }
    
        @Override
        public List<Map> bookPager(Map map, PageBean pageBean) {
            return bookMapper.bookPager(map);
        }
    }

    测试代码

    @Test
        public void selectCacheByPrimaryKey(){
            Book book = bookService.selectByPrimaryKey(17);
            System.out.println(book);
    
            Book book2 = bookService.selectByPrimaryKey(17);
            System.out.println(book2);
    
            Book book3 = bookService.selectByPrimaryKey(33);
            System.out.println(book3);
    
            Book book4 = bookService.selectByPrimaryKey(33);
            System.out.println(book4);
        }

    @CacheEvict:作用是主要针对方法配置,能够根据一定的条件对缓存进行清空 

      

      主要参数说明:

      1)value , key 和 condition 参数配置和@Cacheable一样。

      2) allEntries :

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

      如果指定为 true,则方法调用后将立即清空所有缓存,

      例如:@CachEvict(value=”testcache”,allEntries=true)。

    service层代码

      @CacheEvict(value = "my-redis-cache1",allEntries = true)
        void clear();

    测试代码如下

      @Test
        public void clear(){
            this.bookService.clear();
        }
  • 相关阅读:
    Oracle设置某张表为只读
    greenplum不能下载问题解决方法(转)
    MyBatis学习-入门
    Oracle-数据泵使用
    oracle锁表
    linux查看文件大小
    Apache日志分割
    nginx日志切割
    zookeeper 事务日志查看
    zookeeper连接 org.apache.curator.framework.imps.CuratorFrameworkImpl Background exception was not retry-able or retry gave up [main-EventThread]
  • 原文地址:https://www.cnblogs.com/liuwenwu9527/p/11845511.html
Copyright © 2020-2023  润新知