zoukankan      html  css  js  c++  java
  • Springboot2.x使用redis作为缓存

    一、Springboot2.x关于配置redis作为缓存。

    基本配置如下:

    (1)在application.properties文件中

    spring.redis.database=2 //第几个数据库,由于redis中数据库不止一个
    spring.redis.host=localhost // 也可指定为127.0.0.1
    spring.redis.port=6379 // 默认端口
    spring.redis.password= // 默认为空
    
    # springboot2.x以上如此配置,由于2.x的客户端是lettuce
    # 单位要带上 spring.redis.lettuce.pool.max
    -active=8 spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.max-wait=10000ms spring.redis.lettuce.shutdown-timeout=100ms # springboot1.x如此配置,由于1.x的客户端是jedis #spring.redis.jedis.pool.max-active=8 #spring.redis.jedis.pool.min-idle=0 #spring.redis.jedis.pool.max-idle=8 #spring.redis.jedis.pool.max-wait=-1 #spring.redis.timeout=500

    (2)在pom.xml中

    <!--spring2.0集成redis所需common-pool2-->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
                <version>2.4.2</version>
            </dependency>
    <!-- redis依赖,2.0以上使用这个依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
    <!-- 缓存依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-cache</artifactId>
            </dependency>

    (3)自定义缓存管理器RedisCacheConfig

    package com.xf.spring_test.config;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    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.serializer.*;
    
    import java.time.Duration;
    
    @Configuration
    @EnableCaching
    public class RedisCacheConfig extends CachingConfigurerSupport {
    
        private static final Logger logger = LoggerFactory.getLogger(RedisCacheConfig.class);
    
        // 自定义key生成器
        @Bean
        public KeyGenerator keyGenerator(){
            return (o, method, params) ->{
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName()); // 类目
                sb.append(method.getName()); // 方法名
                for(Object param: params){
                    sb.append(param.toString()); // 参数名
                }
                return sb.toString();
            };
        }
    
        // 配置缓存管理器
        @Bean
        public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofSeconds(60)) // 60s缓存失效
                    // 设置key的序列化方式
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                    // 设置value的序列化方式
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                    // 不缓存null值
                    .disableCachingNullValues();
    
            RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                    .cacheDefaults(config)
                    .transactionAware()
                    .build();
    
            logger.info("自定义RedisCacheManager加载完成");
            return redisCacheManager;
        }
    
      /*  @Bean
        public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){
            RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
            redisTemplate.setConnectionFactory(connectionFactory);
            redisTemplate.setKeySerializer(keySerializer());
            redisTemplate.setHashKeySerializer(keySerializer());
            redisTemplate.setValueSerializer(valueSerializer());
            redisTemplate.setHashValueSerializer(valueSerializer());
            logger.info("序列化完成!");
            return redisTemplate;
        }*/
    
        // key键序列化方式
        private RedisSerializer<String> keySerializer() {
            return new StringRedisSerializer();
        }
    
        // value值序列化方式
        private GenericJackson2JsonRedisSerializer valueSerializer(){
            return new GenericJackson2JsonRedisSerializer();
        }
    }

    (4)在service的实现类中加入需要的注解,即可实现缓存数据

    package com.xf.spring_test.service.impl;
    
    import com.xf.spring_test.dao.PersonDao;
    import com.xf.spring_test.domain.Person;
    import com.xf.spring_test.service.UserService;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
        PersonDao personDao;
    
        public UserServiceImpl(PersonDao personDao) {
            this.personDao = personDao;
        }
    
        @Override
        @Cacheable(cacheNames = "user")
        public Person getUserById(Integer id) {
            return personDao.getUserById(id);
        }
    
        @Override
        @Cacheable(cacheNames = "users")
        public List<Person> getAllUser() {
            return personDao.getAllUser();
        }
    
        @Override
        @CachePut(cacheNames = "updateUser", condition = "#person!=null", unless = "#result>0")
        public Integer editUser(Person person) {
            return personDao.editUser(person);
        }
    
        @Override
        @CacheEvict(cacheNames = "delUser", allEntries = true, beforeInvocation = true,
        condition = "#userId>0")
        public Integer delUser(Integer userId) {
            return personDao.delUser(userId);
        }
    }

     二、注意事项

    (1)要缓存的JAVA对象必须实现Serailizable接口

    (2)必须要配置RedisCacheManager 来管理缓存

    努力有用的话,还要天才做什么呢?
  • 相关阅读:
    整型数字转utf8
    cmake构建时指定编译器架构(x86 or x64)
    tcp echo server libuv
    VS2015编译boost1.62
    android rom开发
    游戏昵称
    乐观锁和悲观锁
    数据库锁机制
    MySQL事务实现原理
    MySQL事务
  • 原文地址:https://www.cnblogs.com/crazy-xf/p/10483180.html
Copyright © 2011-2022 走看看