Redis Cluster Cache with SpringBoot

前提:

根据  https://www.cnblogs.com/luffystory/p/12081074.html

创建好Redis集群

 

 

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.study</groupId>
    <artifactId>SpringBootTest_RedisCluster</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootTest-2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 RedisCacheManager 中使用 configMap 做如下 c1 和 redisCacheConfig 的mapping

 configMap.put("c1" , redisCacheConfig);
如下
@Cacheable(value = "c1")
@Cacheable(vaule = "c2")

c1 存在于configMap 中,因此使用的缓存策略是 configMap 集合中 c1 所对应的缓存策略;
c2 不存在于 configMap 集合中,因此使用的缓存策略是默认的缓存策略。
RedisCacheManager redisCacheManager = new RedisCacheManager(cacheWriter,
        RedisCacheConfiguration.defaultCacheConfig(), configMap);
 
package com.rediscluster.cache;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@Repository
public class BookDao {

    @Cacheable(value = "c1")
    public String getBookById(Integer id) {
    System.out.println("getBookById");
    return "Book : SanGuoYanYi";
    }

    @CachePut(value = "c1")
    public String updateBookById(Integer id) {
    return "Brand new Book : SanGuoYanYi";
    }

    @CacheEvict(value = "c1")
    public void deleteById(Integer id) {
    System.out.println("deleteById");
    }

    @Cacheable(value = "c2")
    public String getBookById2(Integer id) {
    System.out.println("getBookById2");
    return "Book : HongLouMeng";
    }

}

 

package com.rediscluster.cache;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
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;

@Configuration
public class RedisCacheConfig {

    @Autowired
    RedisConnectionFactory conFactory;
    
    @Bean
    RedisCacheManager redisCacheManager() {
    Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
    RedisCacheConfiguration redisCacheConfig = RedisCacheConfiguration.defaultCacheConfig().prefixKeysWith("xluffy:")
        .disableCachingNullValues().entryTtl(Duration.ofMinutes(30));
    
    configMap.put("c1" , redisCacheConfig);
    
    RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(conFactory);
    
    RedisCacheManager redisCacheManager = new RedisCacheManager(cacheWriter,
        RedisCacheConfiguration.defaultCacheConfig(), configMap);
    
    return redisCacheManager;
    }
}

 

package com.rediscluster.cache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class RedisClusterCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisClusterCacheApplication.class, args);
    }

}

 

package com.rediscluster.cache;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@ConfigurationProperties("spring.redis.cluster")
public class RedisConfig {

    List<Integer> ports;
    String host;
    JedisPoolConfig poolConfig;
    
    @Bean
    RedisClusterConfiguration redisClusterConfiguarion() {
    RedisClusterConfiguration configuration = new RedisClusterConfiguration();
    List<RedisNode> nodes = new ArrayList<>();
    for(Integer port : ports) {
        nodes.add(new RedisNode(host,port));
    }
    configuration.setClusterNodes(nodes);
    return configuration;
    }
    
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
    JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguarion(), poolConfig);
        return factory;
    }
    
    @Bean
    RedisTemplate redisTempalte() {
    RedisTemplate redisTempalte = new RedisTemplate();
    redisTempalte.setConnectionFactory(jedisConnectionFactory());
    redisTempalte.setKeySerializer(new StringRedisSerializer());
    redisTempalte.setValueSerializer(new JdkSerializationRedisSerializer());
    
    return redisTempalte;
    }
    
    @Bean
    StringRedisTemplate stringRedisTemplate() {
    StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(jedisConnectionFactory());
    stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
    stringRedisTemplate.setValueSerializer(new StringRedisSerializer());
    
    return stringRedisTemplate;
    }

    public List<Integer> getPorts() {
        return ports;
    }

    public void setPorts(List<Integer> ports) {
        this.ports = ports;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public JedisPoolConfig getPoolConfig() {
        return poolConfig;
    }

    public void setPoolConfig(JedisPoolConfig poolConfig) {
        this.poolConfig = poolConfig;
    }
    
}

 

server:
  port: 8091
spring:
  redis:
    cluster:
      ports:
        - 8001
        - 8002
        - 8003
        - 8004
        - 8005
        - 8006
        - 8007
        - 8008
      host: 192.168.157.131  
      poolConfig:
        max-total: 8
        max-idle: 8
        max-wait-millis: -1
        min-idle: 0
        
        

 

package com.rediscluster.cache;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisClusterCacheApplicationTests {

    @Autowired
    BookDao bookDao;
    
    @Test
    public void contextLoad() {
    bookDao.getBookById(100);
    String book = bookDao.getBookById(100);
    System.out.println(book);
    
    bookDao.updateBookById(100);
    
    String book2 = bookDao.getBookById(100);
    System.out.println(book2);
    
    bookDao.deleteById(100);
    bookDao.getBookById(100);
    
    bookDao.getBookById2(99);
    }
}

 

代码配置好之后 run  RedisClusterCacheApplicationTests as Junit Test, test 通过之后

可以看到方法的参数和返回值已被缓存到 Redis 中。

 

 

 

 
posted @ 2019-12-23 14:27  Happy2Share  阅读(592)  评论(0编辑  收藏  举报