SpringBoot学习笔记(五)——整合redis

本节记录springboot+JPA整合redis实现简单的缓存管理

目录

1、添加redis依赖,并Reload project2

2、配置redis

3、在controller中使用缓存管理

4、测试

SpringCache 的注解


1、添加redis依赖,并Reload project2

<!--redis-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
	<version>2.0.3.RELEASE</version>
</dependency>

2、配置redis

# redis
spring.redis.host=192.168.77.193
spring.redis.port=6379

在启动类DemoJpaApplication上添加@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class DemoJpaApplication {

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

}

3、在controller中使用缓存管理

在BookController的getBook上添加@Cacheable注解

@RequestMapping("/getbook")
@ResponseBody
@Cacheable(cacheNames = "books",unless = "#result==null")
public List<Book> getbook() {
  return bookRepo.findAll();
}

4、测试

访问/book/getbook接口报错,后台报错信息如下:

[Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.io.NotSerializableException: com.galago.demo_jpa.entity.Book] with root cause

从报错信息可看出是Book类没有序列化导致报错。

Book序列化后,重启项目再次访问,未报错,问题解决 

 1)通过浏览器再访问多次,发现数据正常返回,后台没有打印查询语句,说明是从缓存中获取的数据

2)通过redis-cli验证是否存到缓存中,检测如下:

使用@CachePut、@CacheEvict、@Cacheable注解对update和delete实现缓存管理

@RequestMapping("/getbook")
@ResponseBody
@Cacheable(cacheNames = "books",unless = "#result==null")
public List<Book> getbook() {
    return bookRepo.findAll();
}

@RequestMapping("/getByid")
@ResponseBody
@Cacheable(cacheNames = "book")
public Book getOneBook(Integer id) {
    return bookRepo.getById(id);
}

@PostMapping("/add")
@ResponseBody
@CachePut(cacheNames = "book", key="#result.id")
public Book addBook(Book book) {
    return bookRepo.save(book);
}

@RequestMapping("/del")
@ResponseBody
@CacheEvict(cacheNames = "book")
public void deleteById(Integer id) {
    System.out.println(id);
    bookRepo.deleteById(id);
}

 

SpringCache 的注解

 1. 注解说明

@CacheConfig: 一般配置在类上,指定缓存名称,这个名称是和上面“置缓存管理器”中缓存名称的一致。
@Cacheable: 用于对方法返回结果进行缓存,如果已经存在该缓存,则直接从缓存中获取,缓存的key可以从入参中指定,缓存的 value 为方法返回值。
@CachePut: 无论是否存在该缓存,每次都会重新添加缓存,缓存的key可以从入参中指定,缓存的value为方法返回值,常用作于更新。
@CacheEvict: 用于清除缓存
@Caching: 用于一次性设置多个缓存。

2. 常用注解配置参数

value: 缓存管理器中配置的缓存的名称,这里可以理解为一个组的概念,缓存管理器中可以有多套缓存配置,每套都有一个名称,类似于组名,这个可以配置这个值,选择使用哪个缓存的名称,配置后就会应用那个缓存名称对应的配置。
key: 缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合。
condition: 缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存。
unless: 不缓存的条件,和 condition 一样,也是 SpEL 编写,返回 true 或者 false,为 true 时则不进行缓存。

参考:

SpringBoot整合Redis缓存_Sun-yz的博客-CSDN博客_springboot整合redis实现缓存管理中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值