springBoot学习笔记(8)—— 整合redis缓存组件

更多文章

更多系列文章在个人网站

springBoot学习系列笔记文章

springBoot学习笔记(1)—— 搭建springBoot项目



提示:以下是本篇文章正文内容,下面案例可供参考

一、redis是什么?

Redis 是一个使用 C 语言写成的,开源、基于内存、可选持久性的、非关系型,key-value数据库java,Redis 支持的数据类型:String(字符串),list(列表),hash(字典),set(集合),zset(有序集合)。

二、springBoot整合redis缓存的步骤

1. 引入jar包

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
        </dependency>

2. 完整pom内容

<?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 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.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-redis</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-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. application配置内容

spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://数据库地址:3306/springBootAll?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
  cache:
    type: redis
  redis:
    database: 8 #声明使用几号数据库
    host: 127.0.0.1 # Redis server host.
    password: jxkth123456 # Login password of the redis server.
    port: 6379 # Redis server port.
    ssl: false # Whether to enable SSL support.
    timeout: 5000 # Connection timeout
    expire: 3600 # 过期时间

mybatis:
  mapper-locations: classpath:mapper/*.xml

server:
  port: 8081

4.redis序列化配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //过期时间1天
    private Duration timeToLive = Duration.ofDays(1);
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        //默认1
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
        return redisCacheManager;
    }
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
        return redisTemplate;
    }
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }

}

5. service服务

@Service
public class UserService {

    @Resource
    UserDao userDao;

    /***
     * description: 使用注解声明使用缓存,用缓存的键值为userService:用户id,
     * 缓存内容为查询的用户对象
     *  @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
     *  @Cacheable 作用和配置方法
     */
    @Cacheable(value = "userService",key = "#userId")
    public User findUserById(Long userId){
        return userDao.findUserById(userId);
    }

    /**
     *@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和
     * @Cacheable 不同的是,它每次都会触发真实方法的调用
     * @CachePut 作用和配置方法
     */
    @CacheEvict(value = "userService",key = "#user.id")
    public void updateUser(User user){
         userDao.updateUser(user);
    }
    /***
     * description:删除对象,并删除缓存
     * @CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
     * @CacheEvict 作用和配置方法
     */
    @CacheEvict(value = "userService",key = "#userId")
    public int  deleteUserById(Long userId){
        return userDao.deleteUserById(userId);
    }
}

controller,dao,和xml中的查询语句与常规查询语句和方法一致,此处不多赘述。
重点:使用@Cachecable主键声明使用缓存,因为已经配置好了使用redis作为缓存组件,所以可以在redis中查询到缓存对象。

6. 常用缓存注解说明

  1. @Cacheable
    @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
    @Cacheable 作用和配置方法
    在这里插入图片描述
  2. @CachePut
    @CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
    @CachePut 作用和配置方法
    在这里插入图片描述
  3. @CacheEvict
    @CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
    @CacheEvict 作用和配置方法
    在这里插入图片描述

7. 缓存截图

在这里插入图片描述

总结

1. 引入redis相关jar包 2. 配置好redis缓存相关配置 3. 设置redis序列化 4. 使用@Cacheable,@CachePut,@CatcheEvict等相关注解设置缓存

项目源码

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring Boot整合Spring Cloud Alibaba Gateway并使用Redis进行缓存的步骤: 1. 创建Spring Boot工程,添加依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis 在application.properties文件中添加以下配置: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 配置Gateway 在application.yml文件中添加以下配置: ``` spring: cloud: gateway: routes: - id: test_route uri: http://localhost:8080 predicates: - Path=/test/** filters: - name: RequestRateLimiter args: key-resolver: "#{@userKeyResolver}" redis-rate-limiter.replenishRate: 1 redis-rate-limiter.burstCapacity: 2 user: rate-limiter: redis: prefix: "rate-limiter" remaining-key: "remaining" reset-key: "reset" ``` 其中: - id:路由ID - uri:目标服务的URL - predicates:路由断言,此处表示只有访问/test/**的请求才会被路由到目标服务 - filters:路由过滤器,此处使用了RequestRateLimiter过滤器,用于限流 4. 编写Redis限流过滤器 在工程中创建一个RedisRatelimiterFilter类,实现GatewayFilter和Ordered接口,并重写filter方法。 ``` @Component public class RedisRatelimiterFilter implements GatewayFilter, Ordered { private final RedisTemplate<String, String> redisTemplate; private final StringRedisTemplate stringRedisTemplate; private final ObjectMapper objectMapper; public RedisRatelimiterFilter(RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) { this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; this.objectMapper = objectMapper; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String key = "rate-limiter:" + exchange.getRequest().getPath().value(); String remainingKey = key + ":remaining"; String resetKey = key + ":reset"; return redisTemplate.execute(script, Collections.singletonList(remainingKey), "1", "2") .flatMap(result -> { String json = objectMapper.writeValueAsString(result); Map<String, Object> map = objectMapper.readValue(json, Map.class); int remaining = (int) map.get("remaining"); long reset = (long) map.get("reset"); exchange.getResponse().getHeaders().add("X-RateLimit-Remaining", String.valueOf(remaining)); exchange.getResponse().getHeaders().add("X-RateLimit-Reset", String.valueOf(reset)); if (remaining < 0) { exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } return stringRedisTemplate.opsForValue().increment(remainingKey) .flatMap(result2 -> { if (result2.equals(1L)) { stringRedisTemplate.expire(resetKey, Duration.ofMinutes(1)); } return chain.filter(exchange); }); }); } private static final RedisScript<List<Long>> script = RedisScript.of( "local key = KEYS[1]\n" + "local now = tonumber(ARGV[1])\n" + "local rate = tonumber(ARGV[2])\n" + "local capacity = tonumber(ARGV[3])\n" + "local remaining = redis.call('get', key)\n" + "if remaining then\n" + " remaining = tonumber(remaining)\n" + "else\n" + " remaining = capacity\n" + "end\n" + "if remaining == 0 then\n" + " return {0, 0}\n" + "else\n" + " local reset\n" + " if remaining == capacity then\n" + " reset = now + 60\n" + " redis.call('set', key..\":reset\", reset)\n" + " else\n" + " reset = tonumber(redis.call('get', key..\":reset\"))\n" + " end\n" + " local ttl = reset - now\n" + " local ratePerMillis = rate / 1000\n" + " local permits = math.min(remaining, ratePerMillis * ttl)\n" + " redis.call('set', key, remaining - permits)\n" + " return {permits, reset}\n" + "end\n", ReturnType.MULTI, Collections.singletonList("remaining") ); @Override public int getOrder() { return -1; } } ``` 5. 编写KeyResolver 在工程中创建一个UserKeyResolver类,实现KeyResolver接口,并重写resolve方法。 ``` @Component public class UserKeyResolver implements KeyResolver { @Override public Mono<String> resolve(ServerWebExchange exchange) { String userId = exchange.getRequest().getQueryParams().getFirst("userId"); return Mono.justOrEmpty(userId); } } ``` 6. 测试 启动工程,访问http://localhost:8080/test,可以看到返回结果为“Hello, world!”;再次访问http://localhost:8080/test,可以看到返回结果为“Too Many Requests”。 以上就是Spring Boot整合Spring Cloud Alibaba Gateway并使用Redis进行缓存的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值