通过注解完成redis缓存接入

  1. 项目背景
    在一个查询接口中,一般会查询mysql数据库获取数据,或者是通过其他模块来获取数据。为了提高接口响应速度,减轻数据库压力,可以把数据放到redis缓存,同时设置一个过期时间。

  2. 配置redis地址
    这里我们使用的是redisson框架来访问redis

    spring:
      application:
      redis:
        redisson:
          config: |
            singleServerConfig:
              password: 12345678@a
              address: "redis://r-uf6xk594oi83m4be0gpd.redis.rds.aliyuncs.com:6379"
              database: 0
            threads: 0
            nettyThreads: 0
            codec:
              class: "org.redisson.codec.JsonJacksonCodec"
            transportMode: "NIO"
    
  3. pom.xml文件配置

            <dependency>
                <groupId>io.github.causetheneffect</groupId>
                <artifactId>web-common</artifactId>
                <version>1.0.0</version>
            </dependency>
    
  4. 添加redis注解
    对于方法参数和返回值有一定限制,符合要求的才可以使用到缓存
    参数的是:List<>T>
    返回值:Map<T, R>

    @RedisCache(name = "test1")
      public Map<String, User> test1(List<String> list) {
        Map<String, User> map = new HashMap<>();
        // 从数据库或者是调其他项目接口获取数据
        return map;
      }
    
  5. 总结
    以上是本工具类的使用方式,具体原理可以看源码实现:
    https://github.com/causeThenEffect/web-common
    大家可以关注这个项目,以后会不定期分享一些实用高效的后端开发工具,提高开发效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是Java中使用注解操作Redis的示例: 首先,我们需要在pom.xml文件中添加Redis的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 接下来,我们需要在Spring Boot的Application类上添加@EnableCaching注解来开启缓存: ```java @SpringBootApplication @EnableCaching public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 然后,我们需要在Redis的配置文件application.properties中添加Redis的连接信息: ```properties spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= ``` 接下来,我们就可以使用注解来操作Redis了。下面是一个使用注解操作Redis缓存的示例: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Cacheable(value = "userCache", key = "#id") public User getUserById(Long id) { System.out.println("从数据库中获取用户信息"); return userRepository.findById(id).orElse(null); } @CachePut(value = "userCache", key = "#user.id") public User saveUser(User user) { System.out.println("保存用户信息到数据库"); return userRepository.save(user); } @CacheEvict(value = "userCache", key = "#id") public void deleteUserById(Long id) { System.out.println("从数据库中删除用户信息"); userRepository.deleteById(id); } } ``` 上面的示例中,我们使用了三个注解来操作Redis缓存: - @Cacheable:表示方法的结果可以被缓存,如果缓存中有数据,则直接返回缓存数据,否则执行方法并将结果放入缓存中。 - @CachePut:表示方法的结果需要被缓存,每次都会执行方法,并将结果放入缓存中。 - @CacheEvict:表示方法会从缓存中删除数据。 在这个示例中,我们使用了value属性来指定缓存的名称,key属性来指定缓存的键,#id和#user.id是SpEL表达式,用于获取方法参数中的值。 以上就是一个使用注解操作Redis缓存的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值