【SpringBoot】SpringBoot整合Redis(Spring Data Redis)

一、前言:

现在做J2EE开发基本上都用spring全家桶了,由于项目中需要减轻数据库的访问压力,所以考虑添加缓存,之前采用SSM框架的时候对redis进行操作都是用的jedis。其实呢redis的客户端有两种实现方式,一种是调用jedis来实现,二是可以使用spring data redis,通过spring的封装来调用。

二、整合

1、添加redis依赖

<!--与spring Data redis有关,这就是spring data redis-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

2、application.yml配置文件配置redis的相关信息

spring:
  redis:
#host: 127.0.0.1
    host: 192.168.224.225
    port: 6379
    password:		
    

3、配置redis整入spring的缓存框架

import org.springframework.beans.factory.annotation.Autowired;
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.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.cache.interceptor.KeyGenerator;
import java.lang.reflect.Method;
 
 
//配置redis整入spring的缓存框架
 
@Configuration
@EnableCaching  //继承CachingConfigurerSupport并重写方法,配合该注解实现spring缓存框架的使用
public class RedisConfig extends CachingConfigurerSupport {
    /**载入配置文件配置的连接工厂**/
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    /*不提示警告信息*/
    @SuppressWarnings("rawtypes")
    @Autowired
    RedisTemplate redisTemplate;
 
    @Bean
    RedisTemplate<String,Object> objectRedisTemplate(){
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
 
    @Bean 
    @Override
    public CacheManager cacheManager(){
        RedisCacheManager redisCacheManager=new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
//        redisCacheManager.setDefaultExpiration(60);//秒
        return redisCacheManager;
    }
 
    /**
     * 重写缓存key生成策略,可根据自身业务需要进行自己的配置生成条件
     * @return
     */
    @Bean 
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
 
}

至此,springboot整和redis就算配置完啦。

三、实现

真正操作spring data redis中用来真正操作redis的一是采用注解的方式,常用两个注解@Cacheable、@CacheEvit,二是采用RedisTemplate的方式。

众所周知,redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为String、List、Set、Hash、Zset。

RedisTemplate中定义了对5种数据结构的操作

redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

简单示例如下:

  @ApiOperation(value="测试缓存", notes="")
   @RequestMapping(value = "/getAddr", method= RequestMethod.GET)
   public String getAddress() {
       redisTemplate.opsForValue().set("001","河北省");
       Object o = redisTemplate.opsForValue().get("001");
       return o.toString();
   }
   ```
   
  • 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、付费专栏及课程。

余额充值