详解SpringBoot如何使用Redis和Redis缓存

目录
  • 一、配置环境
  • 二、Redis的基本操作
  • 三、使用redis作缓存

一、配置环境

首先,先创建一个SpringBoot项目,并且导入Redis依赖,使用Jedis进行连接测试。

本人的Redis装在虚拟机里,直接切换到虚拟机中的安装目录,启动redis服务,打开redis-cli,如果你设置了密码,还要先输入密码。

cd redis安装目录
#启动redis
redis-server  /etc/redis.conf
#进入redis
redis-cli
#如果你设置了密码
auth 密码

在项目中,设置配置文件

# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/redisdemo?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
#配置mapper xml文件的路径
mybatis-plus.mapper-locations=classpath:com/rh/csdn_redis_demo/mapper/xml/*.xml
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置redis
spring.redis.host=你的redis地址
spring.redis.password=你的redis密码(没有直接空着,或者可以注掉这行)
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

在test中写一个测试方法,测试是否能够连接,返回值为pong

        Jedis jedis = new Jedis("你的redis安装的ip地址",6379);
        //没有密码就注掉这行,不然会报错
        jedis.auth("你的redis密码");//设置密码

        String value = jedis.ping();

        System.out.println(value);

二、Redis的基本操作

首先,要写一个redisconfig的配置类,这个类是为了解决redis存取值的序列化问题和缓存问题。

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解决乱码的问题),过期时间600秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))  //设置数据过期时间600秒
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

定义一个controller,写一个测试方法,进行访问

@RestController
@RequestMapping("redisTest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/test01")
    public void test01(){

        redisTemplate.opsForValue().set("test","redis存值测试");

        String test = (String) redisTemplate.opsForValue().get("test");

        System.out.println(test);

    }

}

在reids中也可以查询key与vaule(中文没有显示是shell的编码问题)。

SpringBoot中进行redis的操作基本都是借助于ops*,各位可以根据自己需求进行其他的选用。

三、使用redis作缓存

简单的用redis做一个缓存,这里使用@Cacheable在方法上作缓存。

写一个用于访问的test02方法,并在该方法上作缓存。

controller

@RestController
@RequestMapping("redisTest")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @GetMapping("/test01")
    public void test01(){

        redisTemplate.opsForValue().set("test","redis存值测试");

        String test = (String) redisTemplate.opsForValue().get("test");

        System.out.println(test);

    }

    @GetMapping("/test02")
    public List<User> test02(){

        List<User> userList = userService.test02();

        System.out.println(userList);

        return null;
    }
}

service

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Cacheable(value = "user",key = "'cache'")
    @Override
    public List<User> test02() {

        List<User> userList = baseMapper.selectList(null);

        return userList;
    }
}

首先查看redis中缓存内容

然后调用方法

可以看到,这一次查询,由于redis中没有缓存,所以对数据库进行了访问,再次查看redis中key

可以看到redis中多出了user::cache这个键,这个就是我们做的缓存了(编码格式问题导致这么显示)

这个时候我们再次访问方法

可以看到,第二次调用方法,并没有连接数据库,没有操作数据库的语句,这表示我们成功的从缓存中取出了数据。

tpis.

如果你在连接redis的时候出现了MISCONF Redis is configured to save RDB snapshots……这样的错误提示,这表示redis的持久化失效了,可以再redis-cli中直接输入config set stop-writes-on-bgsave-error no,但是这种方法不能永远解决这个问题,如果需要永解决这个问题,可以搜索redis持久化失效的解决方法。

以上就是详解SpringBoot如何使用Redis和Redis缓存的详细内容,更多关于SpringBoot使用Redis 缓存的资料请关注我们其它相关文章!

(0)

相关推荐

  • SpringBoot使用Redis缓存的实现方法

    (1)pom.xml引入jar包,如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> (2)修改项目启动类,增加注解@EnableCaching,开启缓存功能,如下: package springboot; import org

  • springboot使用Redis作缓存使用入门教程

    1.依赖与数据库设置 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifact

  • Springboot框架整合添加redis缓存功能

    目录 一:安装Redis 二:添加Redis依赖 三:添加Redis配置信息 四:创建RedisConfigurer 五:创建Redis常用方法 六:接口测试 Hello大家好,本章我们添加redis缓存功能 .另求各路大神指点,感谢 一:安装Redis 因本人电脑是windows系统,从https://github.com/ServiceStack/redis-windows下载了兼容windows系统的redis 下载后直接解压到自定义目录,运行cmd命令,进入到这个文件夹,在这个文件夹下运

  • SpringBoot项目中使用redis缓存的方法步骤

    本文介绍了SpringBoot项目中使用redis缓存的方法步骤,分享给大家,具体如下: Spring Data Redis为我们封装了Redis客户端的各种操作,简化使用. - 当Redis当做数据库或者消息队列来操作时,我们一般使用RedisTemplate来操作 - 当Redis作为缓存使用时,我们可以将它作为Spring Cache的实现,直接通过注解使用 1.概述 在应用中有效的利用redis缓存可以很好的提升系统性能,特别是对于查询操作,可以有效的减少数据库压力. 具体的代码参照该

  • SpringBoot实现redis缓存菜单列表

    因为系统的菜单列表是不轻易改变的,所以不需要在每次请求的时候都去查询数据库,所以,在第一次根据用户id请求到菜单列表的时候,可以把菜单列表的数据缓存在redis里,在第二次请求菜单列表的时候,可以直接在redis缓存里面获取数据,从而减少对数据库的操作,提升性能!首先,我们要下载redis到本地,然后在cmd终端打开redis的src目录,然后运行redis-server即可开启redis本地服务(mac),开启了redis服务后,就要在项目中配置相关的redis的代码了,首先在pom.xml中

  • SpringBoot Redis缓存数据实现解析

    这篇文章主要介绍了SpringBoot Redis缓存数据实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.启用对缓存的支持 spring对缓存的支持有两种方式: a.注解驱动的缓存 b.XML声明的缓存 本文主要介绍纯Java配置的缓存,那么必须在配置类上添加@EnableCaching,这样的话就能启动注解驱动的缓存. 2.使用Redis缓存 缓存的条目不过是一个键值对(Key-Value),其中key描述了产生value的操作和

  • 详解springboot中各个版本的redis配置问题

    今天在springboot中使用数据库,springboot版本为2.0.2.RELEASE,通过pom引入jar包,配置文件application.properties中的redis配置文件报错,提示例如deprecated configuration property 'spring.redis.pool.max-active',猜想应该是版本不对,发现springboot在1.4前后集成redis发生了一些变化.下面截图看下. 一.不同版本RedisProperties的区别 这是spri

  • 详解SpringBoot Redis自适应配置(Cluster Standalone Sentinel)

    核心代码段 提供一个JedisConnectionFactory  根据配置来判断 单点 集群 还是哨兵 @Bean @ConditionalOnMissingBean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory factory = null; String[] split = node.split(","); Set<HostAndPort> nodes =

  • 详解SpringBoot使用RedisTemplate操作Redis的5种数据类型

    目录 1.字符串(String) 1.1 void set(K key, V value):V get(Object key) 1.2 void set(K key, V value, long timeout, TimeUnit unit) 1.3 V getAndSet(K key, V value) 1.4 Integer append(K key, V value) 1.5 Long size(K key) 2.列表(List) 2.1 Long leftPushAll(K key, V

  • 详解SpringBoot如何使用Redis和Redis缓存

    目录 一.配置环境 二.Redis的基本操作 三.使用redis作缓存 一.配置环境 首先,先创建一个SpringBoot项目,并且导入Redis依赖,使用Jedis进行连接测试. 本人的Redis装在虚拟机里,直接切换到虚拟机中的安装目录,启动redis服务,打开redis-cli,如果你设置了密码,还要先输入密码. cd redis安装目录 #启动redis redis-server /etc/redis.conf #进入redis redis-cli #如果你设置了密码 auth 密码 在

  • 详解springboot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

  • 详解springboot+aop+Lua分布式限流的最佳实践

    一.什么是限流?为什么要限流? 不知道大家有没有做过帝都的地铁,就是进地铁站都要排队的那种,为什么要这样摆长龙转圈圈?答案就是为了限流!因为一趟地铁的运力是有限的,一下挤进去太多人会造成站台的拥挤.列车的超载,存在一定的安全隐患.同理,我们的程序也是一样,它处理请求的能力也是有限的,一旦请求多到超出它的处理极限就会崩溃.为了不出现最坏的崩溃情况,只能耽误一下大家进站的时间. 限流是保证系统高可用的重要手段!!! 由于互联网公司的流量巨大,系统上线会做一个流量峰值的评估,尤其是像各种秒杀促销活动,

  • 详解SpringBoot 应用如何提高服务吞吐量

    意外和明天不知道哪个先来.没有危机是最大的危机,满足现状是最大的陷阱. 背景 生产环境偶尔会有一些慢请求导致系统性能下降,吞吐量下降,下面介绍几种优化建议. 方案 1.undertow替换tomcat 电子商务类型网站大多都是短请求,一般响应时间都在100ms,这时可以将web容器从tomcat替换为undertow,下面介绍下步骤: 1.增加pom配置 <dependency> <groupid> org.springframework.boot </groupid>

  • 详解SpringBoot简化配置分析总结

    在SpringBoot启动类中,该主类被@SpringBootApplication所修饰,跟踪该注解类,除元注解外,该注解类被如下自定注解修饰. @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan 让我们简单叙述下它们各自的功能: @ComponentScan:扫描需要被IoC容器管理下需要管理的Bean,默认当前根目录下的 @EnableAutoConfiguration:装载所有第三方的Bean @SpringB

  • 详解SpringBoot的三种缓存技术(Spring Cache、Layering Cache 框架、Alibaba JetCache 框架)

    引言 ​前两天在写一个实时数据处理的项目,项目要求是 1s 要处理掉 1k 的数据,这时候显然光靠查数据库是不行的,技术选型的时候老大跟我提了一下使用 Layering-Cache 这个开源项目来做缓存框架. ​之间问了一下身边的小伙伴,似乎对这块了解不多.一般也就用用 Redis 来缓存,应该是很少用多级缓存框架来专门性的管理缓存吧. ​趁着这个机会,我多了解了一些关于 SpringBoot 中缓存的相关技术,于是有了这篇文章! 在项目性能需求比较高时,就不能单单依赖数据库访问来获取数据了,必

  • 详解SpringBoot通用配置文件(不定时更新)

      以下是SpringBoot项目中的常用配置类.jar包坐标等通用配置 pom文件 <!-- --> <!-- 自定义配置文件提示 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true<

随机推荐