spring boot 整合redis实现方法缓存

本文详细介绍了如何在Spring Boot项目中配置和使用Redis集群,包括pom文件的依赖添加、缓存配置、集群配置,以及实体类和DAO层的实现。通过具体的代码示例,展示了如何进行缓存操作,如读取、更新和删除数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

redis单机搭建:https://www.cnblogs.com/zuidongfeng/p/8032505.html

redis集群搭建请参考:https://blog.youkuaiyun.com/qq_42815754/article/details/82912130


 1、pom文件添加redis引用

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sl</groupId>
    <artifactId>spring-boot-redis-cluster</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.6.RELEASE</version>
        </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-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <!-- redis依赖commons-pool 这个依赖一定要添加 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

    </dependencies>

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

</project>

2、redis缓存配置

@Configuration
public class RedisCacheConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisCacheManager redisCacheManager() {
        Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .prefixKeysWith("zhao:")
                .disableCachingNullValues()
                .entryTtl(Duration.ofMinutes(30));
        configurationMap.put("c1",redisCacheConfiguration);
        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        RedisCacheManager redisCacheManager = new RedisCacheManager(cacheWriter,RedisCacheConfiguration.defaultCacheConfig(),configurationMap);
        return redisCacheManager;
    }
}

 

3、redis集群配置

@Configuration
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterConfig {

    List<Integer> ports;

    String host;

    JedisPoolConfig poolConfig;

    @Bean
    public RedisClusterConfiguration redisClusterConfiguration() {
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        List<RedisNode> nodes = new ArrayList<>();
        for (Integer port:ports) {
            nodes.add(new RedisNode(host,port));
        }
        clusterConfiguration.setClusterNodes(nodes);
        return clusterConfiguration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration(),poolConfig);
        return factory;
    }

    @Bean
    public RedisTemplate redisTemplate() {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        return redisTemplate;
    }

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

 

4、配置文件application.yml

spring:
  redis:
    cluster:
      ports:
        - 7001
        - 7002
        - 7003
        - 7004
        - 7005
        - 7006
      host: 192.168.43.116
      poolConfig:
        max-total: 8
        max-idle : 8
        max-wait-millis: -1
        min-idle: 0
  cache:
    cache-names: c1,c2
    redis:
      time-to-live: 1800s

 

5、实体类和dao层

public class User implements Serializable {

    private String name;

    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}
@Component
public class BookDao {

    @Cacheable(value = "c1")
    public String getBookId(Integer id) {
        System.out.println("getBookId");
        return "张三";
    }

    @CachePut(value = "c1")
    public String updateBookId(Integer id) {
        return "这是李四";
    }

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

    @Cacheable(value = "c1")
    public String getBookById2(Integer id) {
        System.out.println("getBookById2");
        return "这是李四";
    }

}

 

6、测试结果类

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

    @Autowired
    private BookDao bookDao;

    @Test
    public void test() {
        bookDao.getBookId(10);
        String book = bookDao.getBookId(100);
        System.out.println(book);
        bookDao.updateBookId(100);
        String bookId = bookDao.getBookId(100);
        System.out.println(bookId);
        bookDao.deleteById(100);
        bookDao.getBookId(100);
        bookDao.getBookById2(99);
    }
}

 

运行结果: 

张三
这是李四
deleteById
getBookId 

具体代码参考GitHub:https://github.com/FadeHub/spring-boot-learn/tree/master/spring-boot-redis-cluster

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

境里婆娑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值