当前位置:首页 > 技术分析 > 正文内容

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

ruisui882个月前 (03-10)技术分析7

概述

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

准备工作

pom.xml


            redis.clients
            jedis
            2.7.3
        
        
            org.springframework.data
            spring-data-redis
            1.7.2.RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-redis
            RELEASE
        

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 xx(){
        return userMapper.selectAll();
    }
    @RequestMapping("/get3")
    @CacheEvict(value="thisredis")
    @ResponseBody
    public String xx3(){
        return "ok";
    }

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

作者:Python研究者

链接:
https://www.cnblogs.com/chenlove/p/15196475.html

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/2665.html

分享给朋友:

“springboot使用redis(从配置到实战)” 的相关文章

细数5款国外热门Linux发行版

Linux系统已经与我们的生活息息相关,当你用Android手机浏览这篇文章时,你就已经在使用Linux系统。当然作为编程开发最热门的系统,他还有很多专注于开发使用的版本。Fedora热门入门推荐,一款优秀的程序猿专供Linux发行版,自带开发者门户,集成大量教程指南、开发集成环境、虚拟机等工具,简...

微软的Linux发行版终于加入了对XFS根文件系统的支持

当许多Linux发行版在评估新的根文件系统选项或甚至像OpenZFS这样的特性,微软内部Linux发行版到本月才开始支持XFS作为根文件系统选项。随着这个月对微软内部Linux发行版CBL-Mariner的更新,他们现在支持XFS作为根文件系统。到目前为止,这个用于微软内部各种目的的Linux发行版...

Beta版Linux Mint“Xia”发行版22.1发布

IT之家 12 月 13 日消息,Beta 版 Linux Mint“Xia” 22.1 昨日(12 月 12 日)发布,新版本基于 Ubuntu 24.04,内核版本为 Linux 6.8,长期支持将持续到 2029 年,为用户提供可靠稳定的使用体验。新版本在软件包管理方面,主要弃用了传统的 ap...

vue中组件之间的通信方式

** 1.1 父子组件**a. 父向子传数据: 第1种: 父通过属性传值,子组件通过props接收数据(注:props传过来的数据是单向的,不可以进行修改)第2种:子组件可以通过$parent来获取父组件里的数据和调用父组件的方法(注:数据是双向的,还要注意如用了UI组件并且在该UI组件里重新定义一...

高效使用 Vim 编辑器的 10 个技巧

在 Reverb,我们使用 MacVim 来标准化开发环境,使配对更容易,并提高效率。当我开始使用 Reverb 时,我以前从未使用过 Vim。我花了几个星期才开始感到舒服,但如果没有这样的提示,可能需要几个月的时间。这里有十个技巧可以帮助你在学习使用 Vim 时提高效率。1. 通过提高按键重复率来...

双子座应用程序推出模型切换器以在Android上访问2.0

#头条精品计划# 快速导读谷歌推出了Gemini 2.0 Flash实验版,现已在其安卓应用中可用,之前仅在gemini.google.com网站上提供。新版本的15.50包含模型切换器,用户可以在设置中选择不同模型,包括1.5 Pro、1.5 Flash和2.0 Flash实验版。谷歌提醒,2.0...