springboot项目使用redis数据库作缓存

1.导入jar包,用maven和springboot构建项目:

    

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

2.redis数据库连接地址配置,配置文件里加入:

    

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.118.111
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

3.redis键生成策略配置类

    

package com.winstar.redis;
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.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 java.lang.reflect.Method;


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    private final static String redis_key_questions="ACTIVITY_QUESTION";
    private final static String redis_key_annual="ACTIVITY_ANNUAL";
    private final static String redis_key_action="ACTIVITY_ACTION";


    @Bean
    public KeyGenerator ACTIVITY_QUESTION_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {

                return redis_key_questions;
            }
        };

    }

    @Bean
    public KeyGenerator ACTIVITY_ACTION_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {

                return redis_key_action;
            }
        };

    }

    @Bean
    public KeyGenerator ACTIVITY_ANNUAL_KEY(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {

                return redis_key_annual;
            }
        };

    }

    @Bean
    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();
            }
        };

    }

    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        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);
        template.afterPropertiesSet();
        return template;
    }
}

4.使用缓存

    

package com.winstar.service.annualReport;

import com.winstar.entity.annualReport.District;
import com.winstar.entity.annualReport.IllegalAction;
import com.winstar.repository.annualReport.DistrictRepository;
import com.winstar.repository.annualReport.IllegalActionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shoo on 2018/1/10 10:43.
 *         --
 */
@Service
public class AnnualReportsService {
    Logger logger = LoggerFactory.getLogger(AnnualReportsService.class);
    @Autowired
    private DistrictRepository districtRepository;
    @Autowired
    private IllegalActionRepository illegalActionRepository;

    @Cacheable(cacheNames = "ACTIVITY_ANNUAL", keyGenerator = "ACTIVITY_ANNUAL_KEY")
    public List<District> getDistricts(){
        logger.info("getDistricts");
        return districtRepository.findAll();
    }

    @Cacheable(cacheNames = "ACTIVITY_ACTION", keyGenerator = "ACTIVITY_ACTION_KEY")
    public List<IllegalAction> getIllegalActions(){
        logger.info("getIllegalActions");
        return illegalActionRepository.findAll();
    }
}
      注意:缓存的查询方法最好写在service里

      1.其实就是在原来的查询方法上添加 Cacheable 注解 ,这样调用该方法查询时就会先从redis数据库缓存里查对应的键(如上面代码的 ACTIVITY_ACTION),如果没有则从mysql里查询,并把结果以键值对的方式放入redis缓存里,后面再查询还是先判断缓存,缓存里存在就直接得到结果,不会再从mysql里查询。

      2. 注解 Cacheable 的 cacheNames 对应着redis配置类里的 键,keyGenerator对应着配置类里的键生成策略bean

5.刷新缓存

    刷新缓存就是在redis缓存里把相应的键移除(delete),这里使用的是代码操作移除:

 /**
     * 刷新redis缓存
     * @return
     */
    @PutMapping("/refresh")
    public String refresh(){
        if(redisTemplate.hasKey("ACTIVITY_ANNUAL")){
            redisTemplate.delete("ACTIVITY_ANNUAL");
        }
        if(redisTemplate.hasKey("ACTIVITY_ACTION")){
            redisTemplate.delete("ACTIVITY_ACTION");
        }
        return "ok";
    }
     在你需要刷新缓存的地方调用此方法

     当然你也可以通过redis客户端管理工具 RedisDesktopManager 连接到redis 手动移除

     还可以通过配置文件里表达式,定时移除





评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值