springboot使用redis(从配置到实战)

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring支持的注解进行访问缓存.

概述

springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring支持的注解进行访问缓存.

准备工作

pom.xml

<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>RELEASE</version>
        </dependency>

application.properties

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0

Redis配置类

package cn.chenlove.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
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 redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
public class RedisConfig  extends CachingConfigurerSupport{
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWaitMillis;

    @Bean
    public JedisPool redisPoolFactory() {
        Logger.getLogger(getClass()).info("JedisPool注入成功!!");
        Logger.getLogger(getClass()).info("redis地址:" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);

        return jedisPool;
    }
}

可以看出,我们这里主要配置了两个东西,cacheManager方法配置了一个缓存名称,它的名字叫做thisredis,当我们要在方法注解里面使用到它的时候,就要根据名称进行区分不同缓存.同时设置了缓\
存的过期时间.redisTemplate则是比较常见的,我们设置了RedisTemplate,因此在代码里面,我们也可以通过@Autowired注入RedisTemplate来操作redis.

 

使用

 

接下来就是如何使用注解啦,这一步反而是最简单的.其实只用到了两个注解,@Cacheable和@CacheEvict.第一个注解代表从缓存中查询指定的key,如果有,从缓存中取,不再执行方法.如果没有则执\
行方法,并且将方法的返回值和指定的key关联起来,放入到缓存中.而@CacheEvict则是从缓存中清除指定的key对应的数据.使用的代码如下:

//有参数
    @Cacheable(value="thisredis", key="'users_'+#id")
    public User findUser(Integer id) {
        User user = new User();
        user.setUsername("hlhdidi");
        user.setPassword("123");
        user.setUid(id.longValue());
        System.out.println("log4j2坏啦?");
        logger.info("输入user,用户名:{},密码:{}",user.getUsername(),user.getPassword());
        return user;
     }

      @CacheEvict(value="thisredis",   key="'users_'+#id",condition="#id!=1")
      public void delUser(Integer id) {
        // 删除user
           System.out.println("user删除");
       }

       //无参数
       @RequestMapping("/get")
    @Cacheable(value="thisredis")
    @ResponseBody
    public List<User> xx(){
        return userMapper.selectAll();
    }
    @RequestMapping("/get3")
    @CacheEvict(value="thisredis")
    @ResponseBody
    public String xx3(){
        return "ok";
    }

可以看出,我们用@Cacheable的value属性指定具体缓存,并通过key将其放入缓存中.这里key非常灵活,支持spring的el表达式,可以通过方法参数产生可变的key(见findUser方法),也可以通过其指定在\
什么情况下,使用/不使用缓存(见delUser方法).

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
17天前
|
NoSQL 测试技术 Go
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
|
19天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
43 3
|
4天前
|
Java 数据库 Spring
springboot 解耦、隔离、异步的原则以及实战
【5月更文挑战第30天】在Spring Boot中实现解耦、隔离和异步的原则,能够提升应用程序的可维护性、可扩展性和性能。下面我会先介绍这三个原则的基本概念和意义,然后通过实战示例展示如何在Spring Boot应用中应用这些原则。
23 1
|
6天前
|
NoSQL Linux Redis
Centos7 安装和配置 Redis 5 教程
在Centos上安装Redis 5,如果是 Centos8,那么 yum 仓库中默认的 redis 版本就是 5,直接 yum install 即可。
36 0
|
6天前
|
JSON JavaScript Java
SpringBoot读取配置优先级顺序是什么?
Spring Boot的外部配置加载优先级是开发者理解和管理应用程序配置的关键。它支持多种配置源,包括Java属性文件、YAML文件、环境变量、命令行参数等。配置加载顺序从低到高为:默认属性、@PropertySource加载的配置、Config Data(内部配置文件、外部配置文件)、环境变量、系统属性、Servlet容器初始化参数、SPRING_APPLICATION_JSON格式的环境变量或系统属性以及命令行参数。了解这一顺序有助于在不同环境中灵活配置和管理Spring Boot应用,确保其按预期运行。
|
6天前
|
IDE Java Maven
Springboot中Processor注解概念以及实战案例
【5月更文挑战第28天】在Spring Boot中,没有直接名为Processor的注解。不过,你可能是在谈论与Spring Boot相关的注解处理器(Annotation Processors)的概念,尤其是在处理自定义注解或@ConfigurationProperties注解时的情况。
19 1
|
6天前
|
NoSQL Java Redis
SpringBoot 操作 Redis
SpringBoot 操作 Redis
30 2
|
8天前
|
Java 数据库连接 网络安全
springboot使用Pivotal Greenplum JDBC如何进行配置
【5月更文挑战第23天】springboot使用Pivotal Greenplum JDBC如何进行配置
33 6
|
10天前
|
Java 应用服务中间件 Maven
SpringBoot概述&SpringBoot基础配置&yml的使用&多环境启动
SpringBoot概述&SpringBoot基础配置&yml的使用&多环境启动
24 2
|
11天前
|
Java Python Spring
小唐开始学 Spring Boot——(2)Spring Boot核心配置与注解
小唐开始学 Spring Boot——(2)Spring Boot核心配置与注解