springboot用redis做缓存

springboot 使用 redis作为缓存,简单的demo

安装redis

windows安装

下载地址
解压之后启动redis服务
redis-server.exe redis.windows.conf
然后使用客户端连接,redis-cli.exe可以连接默认是 127.0.0.1:6379
在这里插入图片描述
在这里插入图片描述

搭建springboot+redis项目

使用的工具是idea
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
pom.xml文件内容

 <?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.mucong</groupId>
    <artifactId>springbootrediscache</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.8</version>
        </dependency>

    </dependencies>
</project>

代码

为了测试效果,我们设计了一个接口获取当前的时间,这样每次获取的都是最新的时间,如果增加了缓存,就可能获取之前的时间,实际项目中不能这么用,实际项目为了保证接口的幂等性,如果有时间的话,一般会把时间作为参数。

项目结构
在这里插入图片描述
App.java

package com.mucong.srcache;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

}

DemoController.java
ppackage com.mucong.srcache.controller;


import com.mucong.srcache.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private DemoService demoService;

    @GetMapping("/getNow")
    public String getNow(String key) throws Exception{
        return demoService.getTime(key);
    }

}

DemoService.java
package com.mucong.srcache.service;

public interface DemoService {
    String getTime(String key);
}

DemoServiceImpl.java
package com.mucong.srcache.service.impl;

import com.mucong.srcache.service.DemoService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public String getTime(String key) {
        return LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
    }
}

RedisConf.java
package com.mucong.srcache.conf;

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.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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConf extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))

                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();

        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                // 可以给每个cacheName不同的RedisCacheConfiguration  设置不同的过期时间
                //.withCacheConfiguration("Users",config.entryTtl(Duration.ofSeconds(100)))
                .transactionAware()
                .build();
        return cacheManager;
    }
}

application.yml
server:
  port: 9000
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: #默认是不需要的
    jedis:
      pool:
        max-active: 8
    timeout: 5000
#logging:
#  level:
#    root: debug

不缓存的测试

上面的代码还没有添加缓存

启动项目
在这里插入图片描述

浏览器中输入 http://localhost:9000/demo/getNow/abc
每次刷新返回的时间都不同
!在这里插入图片描述

了解几个注解

简单介绍几个注解,待会要用到

  • @EnableCaching
  • @Cacheable
  • @CachePut
  • @Caching
  • @CacheConfig
  • @CacheEvict
注解说明作用对象
EnableCaching开启缓存的开关,放到配置类上,也可以直接放到App上全局的
CacheConfig标注到类上,主要设置公共属性,缓存空间,key生成策略,缓存管理器设置的类内部
Cacheable标注到方法上,使用缓存的主方法,逻辑是,根据key如果有缓存则返回缓存数据,没有则执行方法,并且把数据放入缓存方法上
CachePut放到方法上,更新缓存,方法的返回值根据设置的key值放入缓存方法上
CacheEvict放到方法上,清除缓存,一般设置在编辑或者删除操作的方法上,清除对应key值的缓存方法上
Cachingdiy方式方法上

添加缓存测试

通过上面的注解,我们首先需要开启缓存,在App.java中添加注解@EnableCaching,
然后修改DemoServiceImpl.java,然后重启项目。

在这里插入图片描述
在这里插入图片描述

刷新页面发现每次时间都相同,修改key值之后,可以返回时间

在这里插入图片描述

查看redis里面的缓存

使用的工具是 redisDesktopManager,可以看到里面的缓存有个时间,TTL缓存失效的时间单位是秒。

在这里插入图片描述

设置缓存失效时间

在RedisConf.java文件中,修改里面的参数,我们可以设置到application.yml中

在这里插入图片描述

在文件中设置属性,默认我们用600秒

在这里插入图片描述

修改代码

在这里插入图片描述

现在我们可以在application.yml中设置过期时间了,使用后发现时间变长了
在这里插入图片描述

在这里插入图片描述

总结

这里只是简单介绍一下应用,我们在使用中会发现会有很多细节需要掌握,比如过期策略,缓存穿透,雪崩,key冲突,还有redis单点到哨兵模式,这些我们都可以一点一点使用中摸索出来。

需要源码可以访问:
githup
gitee

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以很方便地与Redis进行整合,实现缓存功能。在使用之前,需要先引入相关的依赖,如spring-boot-starter-data-redis和jedis等。然后,通过配置文件或者编码方式,配置Redis的连接信息和相关参数。最后,在需要使用缓存的地方,可以使用Spring Boot提供的注解@Cacheable来实现缓存功能。这样,就可以很方便地使用Redis作为缓存,提高系统的性能和响应速度。 ### 回答2: Spring Boot是构建基于Spring框架的Web应用程序的快速开发框架,它通过简化配置和提高开发效率,让开发人员专注于实现业务逻辑。Redis是一种快速、高性能的非关系型内存数据库,与Spring Boot框架结合使用,可以实现高效的数据缓存Spring BootRedis的整合可以采用Jedis和Lettuce两种不同的Redis客户端,本文将分别介绍这两种集成方式的具体实现。 Jedis是一个高性能的Java Redis客户端,使用起来非常简单。在Spring Boot中使用Jedis,首先需要添加Jedis的依赖: ``` <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> ``` 然后,在应用程序的配置文件中配置Redis的连接信息: ``` spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 在Java代码中,可以通过注入JedisPool对象来获取Jedis连接: ``` @Autowired private JedisPool jedisPool; public void set(String key, String value) { try (Jedis jedis = jedisPool.getResource()) { jedis.set(key, value); } } ``` Lettuce是另一款Redis客户端,它支持异步和响应式编程,具有更高的性能和更好的扩展性。在Spring Boot中使用Lettuce,首先需要添加Lettuce的依赖: ``` <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </dependency> ``` 然后,在应用程序的配置文件中配置Redis的连接信息: ``` spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 在Java代码中,可以通过注入LettuceConnectionFactory对象来获取Redis连接: ``` @Autowired private LettuceConnectionFactory lettuceConnectionFactory; public void set(String key, String value) { try (RedisConnection connection = lettuceConnectionFactory.getConnection()) { connection.set(key.getBytes(), value.getBytes()); } } ``` 以上是两种集成Redis的方式,开发人员可以根据实际需求选择适合自己的方式。需要注意的是,Redis作为一种内存数据库,其缓存的数据是暂存在内存中的,因此需要根据实际的数据存储情况和内存容量来合理配置缓存的过期时间和内存容量。</div> ### 回答3: Spring Boot 是一款非常优秀的 JavaEE 程序快速开发框架,它的出现真正实现了开发者可以轻松快速的开发高可用和高效率的JavaEE程序。 在开发过程中,我们一定会遇到很多存储问题,比如数据库存储、文件存储、图片存储等等。其中,对于一些需要频繁读取的数据,我们可以考虑使用缓存技术来提高效率,Redis 就是很好的一种缓存技术。 Redis 是一个内存中的数据结构存储系统,支持多种类型的数据结构,如字符串、哈希、列表等。在应用程序中,我们可以将报表、热门商品、用户信息、验证码等频繁使用的数据存放到 Redis 中,减轻数据库的负担,提高应用程序的响应速度。 下面我们就来说明如何在 Spring Boot 中整合 Redis 作为缓存。 首先,需要在pom.xml文件中导入Redis的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 然后,在 application.properties 配置文件中配置 Redis 的连接信息: ``` spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=10000 ``` 接着,在程序中定义 RedisTemplate,用于操作 Redis 数据库: ``` @Configuration public class RedisConfig { @Bean JedisConnectionFactory jedisConnectionFactory() { return new JedisConnectionFactory(); } @Bean RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 在 Service 层中,我们可以使用 Redis 缓存相关的注解,实现 Redis缓存功能。 @Cacheable:在方法执行前,Spring 先查看缓存中是否有数据,如果有则直接返回缓存数据;如果没有,则调用方法并将方法返回值缓存起来。适用于查询操作。 @CachePut:无论怎么样,都会执行方法,并将方法返回值缓存,适用于更新操作。 @CacheEvict:删除缓存数据,当某个数据已经不再使用时,可以删除相应的缓存数据。适用于删除操作。 示例代码如下: ``` @Service @CacheConfig(cacheNames = "user") public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override @Cacheable public User getUserById(Long id) { Optional<User> userOptional = userRepository.findById(id); return userOptional.orElse(null); } @Override @CachePut(key = "#user.id") public User updateUser(User user) { userRepository.save(user); return user; } @Override @CacheEvict(key = "#id") public void deleteUserById(Long id) { userRepository.deleteById(id); } } ``` 最后,在启动类中添加注释@EnableCaching,启用缓存: ``` @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 以上就是使用 Spring BootRedis 实现缓存的方法。通过使用 Redis 作为缓存,我们可以极大的提高应用程序的性能和响应速度,同时提高用户的体验和满意度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值