springboot集成redis


首先導入pom依賴:

1 <dependency>
2         <groupId>org.springframework.boot</groupId>
3         <artifactId>spring-boot-starter-data-redis</artifactId>
4     </dependency>
5     <dependency>
6         <groupId>redis.clients</groupId>
7         <artifactId>jedis</artifactId>
8     </dependency>

配置application.yml文件:

 1 spring:
 2   redis:
 3       database: 0
 4       host: 192.168.147.144
 5       port: 6379
 6       password: 123456
 7       jedis:
 8           pool:
 9               max-active: 100
10               max-idle: 3
11               max-wait: -1
12               min-idle: 0
13       timeout: 1000

導入redis配置類  RedisConfig:

package com.cjh.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 :緩存的條件,可以為空,

server

1  @Cacheable(value = "my-redis-cache2",key = "'book'+#bid",condition = "#bid<20")
2     Book selectByPrimaryKey(Integer bid);

測試:

  @Test
    public void selectByPrimaryKey(){
        Book book = bookService.selectByPrimaryKey(36);
        System.out.println(book);

    }

第一次是查數據庫如果在1分鍾以內查詢就是從緩存中拿數據

@CachePut:作用是主要針對方法配置,能夠根據方法的請求參數對其結果進行緩存,和 @Cacheable 不同的是,它每次都會觸發真實查詢

  方法的調用 

  主要參數說明:

  參數配置和@Cacheable一樣

 1 @CachePut(value = "my-redis-cache2") 2 Book selectByPrimaryKey1(Integer bid); 

測試:

   @Test
    public void selectByPrimaryKey1(){
        Book book = bookService.selectByPrimaryKey1(36);
        Book book2 = bookService.selectByPrimaryKey1(39);
        Book book3 = bookService.selectByPrimaryKey1(40);

        System.out.println(book);
        System.out.println(book2);
        System.out.println(book3);

    }

@CacheEvict:作用是主要針對方法配置,能夠根據一定的條件對緩存進行清空 

  

  主要參數說明:

  1)value , key 和 condition 參數配置和@Cacheable一樣。

  2) allEntries :

  是否清空所有緩存內容,缺省為 false,

  如果指定為 true,則方法調用后將立即清空所有緩存,

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

server

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

impl

    @Override
    public void clear() {
        System.out.println("清空緩存");
    }

測試:

  @Test
    public void clear(){
        bookService.clear();
    }

結果就是把redis中的數據都清空了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM