在SpringBoot中添加Redis

前言

在實際的開發中,會有這樣的場景。有一個微服務須要提供一個查詢的服務,可是須要查詢的數據庫表的數據量十分龐大,查詢所須要的時間很長。
此時就能夠考慮在項目中加入緩存。java

引入依賴

在maven項目中引入以下依賴。而且須要在本地安裝redis。redis

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

配置redis

在SpringBoot的配置文件中添加以下代碼。spring

redis:
    host: 127.0.0.1
    port: 6379
    timeout: 5000
    database: 0
    jedis:
      pool:
        max-idle: 8
        max-wait:
        min-idle: 0

添加redis配置文件

新建名爲RedisConfig的配置類。數據庫

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.cache.RedisCacheWriter;
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.time.Duration;

/**
 * RedisConfig
 *
 * @author detectiveHLH
 * @date 2018-10-11 14:39
 **/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, 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 RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        //redis序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 自定義CacheManager
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        //全局redis緩存過時時間
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}

添加緩存配置

在項目的service層中的實現類中,添加@Cacheable註解。api

import java.util.HashMap;

/**
 * UserLoginServiceImpl
 *
 * @author detectiveHLH
 * @date 2018-10-10 17:20
 **/
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    @Cacheable(value = "usercache")
    public HashMap getByUserName(String userName) {
        System.out.println("此時沒有走緩存");
        return userLoginMapper.getByUserName(userName);
    }
}

而後調用一次該接口。就能夠在redis中看到以下的key。緩存

"usercache::com.detectiveHLH.api.service.impl.UserLoginServiceImplgetByUserNameSolarFarm"

同時,能夠在控制檯中看到有"此時沒有走緩存"的輸出。而後再次調用該接口,就能夠看到返回的速度明顯變快,而且沒有"此時沒有走緩存"輸出。說明
此時的接口走的是緩存。app

相關文章
相關標籤/搜索