springboot配置redis缓存数据库查询

直接上干货

1、引入redis依赖(版本号可以不指定)

<!--缓存-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.5.RELEASE</version>
</dependency>

2、在yml或者properties文件中配置redis的连接信息

spring:
  profiles:
    active: dev #开发环境
  application:
      name: service-feign-orders
  datasource:
      name: test
      url: jdbc:mysql://120.78.89.12:3306/paixi_1_0_test?useUnicode=true&characterEncoding=UTF-8
      username: paixiuser
      password: Paixi123!@#
      # 使用druid数据源
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 20
      initialSize: 1
      maxWait: 60000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20
  #redis缓存 单机版
  redis:
      host: 192.168.0.150
      port: 6379
      maxTotal: 200
      pool:
        max-active: 8
        min-idle: 0
        max-idle: 8
        max-wait: 10000
      timeout: 0

3、创建一个数据库缓存配置类继承CachingConfigurerSupport,做个性化修改。例如缓存key的生成策略,缓存的时间等。示例:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
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.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 * @author zhaoxi
 * @date 2018/11/1 15:34
 * TODO: 数据库缓存配置类
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;

    //自定义缓存key生成策略
//    @Bean
//    public KeyGenerator keyGenerator() {
//        return new KeyGenerator(){
//            @Override
//            public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
//                StringBuffer sb = new StringBuffer();
//                sb.append(target.getClass().getName());
//                sb.append(method.getName());
//                for(Object obj:params){
//                    sb.append(obj.toString());
//                }
//                return sb.toString();
//            }
//        };
//    }

    /**
     * TODO: 缓存管理器
     *
     * @return
     * @throws
     * @author zhaoxi
     * @time 2018/11/1 15:07
     * @params
     */
    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        /**
         * 设置缓存过期时间
         */
        cacheManager.setDefaultExpiration(300);//单位为秒
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template);//设置序列化工具
        template.afterPropertiesSet();
        return template;
    }

    private void setSerializer(StringRedisTemplate template) {
        @SuppressWarnings({"rawtypes", "unchecked"})
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
    }
}

4、配置对应的缓存,一般基于mapper类缓存。例如:

import com.paixi.model.Orders;
import com.paixi.model.vo.OrdersGiftView;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
@CacheConfig(cacheNames = "ordersMapper")
public interface OrdersMapper {

    int insert(Orders record);
     //缓存此方法,key为方法名+id
    @Cacheable(key = "'selectByPrimaryKey'+#p0")
    Orders selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(Orders record);
    }

附录:
@CacheConfig
有时候一个类中可能会有多个缓存操作,而这些缓存操作可能是重复的。这个时候可以使用@CacheConfig
@Cacheable
用来声明方法是可缓存的。将结果存储到缓存中以便后续使用相同参数调用时不需执行实际的方法。直接从缓存中取值。最简单的格式需要制定缓存名称;
@CachePut
如果缓存需要更新,且不干扰方法的执行,可以使用注解@CachePut。@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
@CacheEvict
spring cache不仅支持将数据缓存,还支持将缓存数据删除。此过程经常用于从缓存中清除过期或未使用的数据。
@CacheEvict要求指定一个或多个缓存,使之都受影响。此外,还提供了一个额外的参数allEntries 。表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素。
其他的注解元素的作用请查看官方文档
5、可针对指定的key配置缓存失效时间

缓存管理配置类修改为如下设置,springboot提供了RedisCachePrefix接口进行配置

/**
 * TODO: 缓存管理器
 *
 * @return
 * @throws
 * @author zhaoxi
 * @time 2018/12/7 12:57
 * @params
 */
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
    //CacheManager cacheManager = new RedisCacheManager(redisTemplate);
    //return cacheManager;
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    // 缓存前缀
    RedisCachePrefix cachePrefix = new {
        @Override
		public byte[] prefix(String cacheName) {
    		return new byte[0];
    		}
    }
    cachePrefix.prefix("select");
    cachePrefix.prefix("cache_sql_");
    rcm.setCachePrefix(cachePrefix);
    //设置指定前缀的缓存默认过期时间(秒)
    rcm.setDefaultExpiration(300);
    return rcm;
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值