广告
返回顶部
首页 > 资讯 > 数据库 >使用springBoot集成redis的案例
  • 873
分享到

使用springBoot集成redis的案例

2024-04-02 19:04:59 873人浏览 安东尼
摘要

小编给大家分享一下使用SpringBoot集成Redis的案例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!springboot

小编给大家分享一下使用SpringBoot集成Redis的案例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。

Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的api

它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

reids的优点

以下是Redis的一些优点:

  • 异常快 - Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。

  • 支持丰富的数据类型 - Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。

  • 操作具有原子性 - 所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值。

  • 多实用工具 - Redis是一个多实用工具,可用于多种用例,如:缓存消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,WEB应用程序中的会话,网页命中计数等。

Redis 安装


Window 下安装

下载地址:https://GitHub.com/MSOpenTech/redis/releases。

Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 C 盘,解压后,将文件夹重新命名为 redis。

打开一个 cmd 窗口 使用cd命令切换目录到 C:\redis

运行 redis-server.exe redis.windows.conf

如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:

使用springBoot集成redis的案例

集成redis


我们还是延用上一章的项目:Springboot集成SpringCloud-config实现dataSource热部署

1、添加依赖

<!--集成redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastJSON</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

2、在配置中心里添加redis配置

spring.redis.host=127.0.0.1
#Redis服务器连接端口
spring.redis.port=6379
#Redis服务器连接密码(默认为空)
spring.redis.passWord=
#连接池最大连接数(使用负值表示没有限制)
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=30000

3、配置类RedisConfig

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachinGConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cloud.context.config.annotation.RefreshScope;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2jsonRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
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.password}")
    private String password;
    @Value("${spring.redis.pool.max-active}")
    private int maxActive;
    @Value("${spring.redis.pool.max-wait}")
    private int maxWait;
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;
    
    @RefreshScope
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        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();
            }
        };
    }
    
    @RefreshScope
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout); //设置连接超时时间
        factory.setPassword(password);
        factory.getPoolConfig().setMaxIdle(maxIdle);
        factory.getPoolConfig().setMinIdle(minIdle);
        factory.getPoolConfig().setMaxTotal(maxActive);
        factory.getPoolConfig().setMaxWaitMillis(maxWait);
        return factory;
    }
    
    @RefreshScope
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(10); //设置key-value超时时间
        return cacheManager;
    }
    
    @RefreshScope
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
        template.afterPropertiesSet();
        return template;
    }
    
    @RefreshScope
    private void setSerializer(StringRedisTemplate template) {
        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.setValueSerializer(jackson2JsonRedisSerializer);
    }
}

4、RedisUtils类

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;
    
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
    
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0){
            redisTemplate.delete(keys);
        }
    }
    
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }
    
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }
    
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }
    
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }
    
    public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }
    
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }
    
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }
    
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

5、测试,修改controller

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chenqi.springboot.redis.RedisUtils;
import com.chenqi.springboot.service.TestService;
@RestController
public class SpringBootController {
    
    public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
    
    @Autowired
    TestService testService;
    
    @Autowired
    private RedisUtils redisUtils;
    @RequestMapping(value = "/hello/{id}")
    public String hello(@PathVariable(value = "id") String id){
        //查询缓存中是否存在
        boolean hasKey = redisUtils.exists(id);
        String str = "";
        if(hasKey){
            //获取缓存
            Object object =  redisUtils.get(id);
            log.info("从缓存获取的数据"+ object);
            str = object.toString();
        }else{
            //从数据库中获取信息
            log.info("从数据库中获取数据");
            str = testService.test();
            //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
            redisUtils.set(id,str,10L,TimeUnit.MINUTES);
            log.info("数据插入缓存" + str);
        }
        return str;
    }
}

启动项目,第一次访问:Http://localhost:8002/hello/111
使用springBoot集成redis的案例
使用springBoot集成redis的案例


通过控制台输出,我们可以看到是从数据库中获取的数据,并且存入了redis缓存中。

我们再次刷新浏览器

使用springBoot集成redis的案例
可以看到,第二次是从缓存中读取的,我们试试不断刷新浏览器

使用springBoot集成redis的案例
可以看到,之后都是从缓存中获取的。

到此我们的redis就配置好了。

以上是“使用springBoot集成redis的案例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网数据库频道!

您可能感兴趣的文档:

--结束END--

本文标题: 使用springBoot集成redis的案例

本文链接: https://www.lsjlt.com/news/55526.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用springBoot集成redis的案例
    小编给大家分享一下使用springBoot集成redis的案例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!springboot...
    99+
    2022-10-18
  • SpringBoot集成Redis实现验证码的简单案例
    目录一、下载安装Redis二、代码部分总结前言 一次学习过程中简单的记录 一、下载安装Redis 这里就不多说了,下载安装好Redis,最好是把Redis Desktop Manag...
    99+
    2022-11-12
  • SpringBoot集成redis的示例分析
    这篇文章给大家分享的是有关SpringBoot集成redis的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。如何使用springBoot集成redis 定义REmote ...
    99+
    2022-10-18
  • SpringBoot集成redis的示例代码
    目录前言一、redis是什么二、集成redis步骤三、代码演示前言 redis想必小伙伴们即使没有用过,也是经常听到的,在工作中,redis用到的频率非常高,今天详细介绍一下Spr...
    99+
    2022-11-12
  • SpringBoot集成Redis使用Lettuce
            Redis是最常用的KV数据库,Spring 通过模板方式(RedisTemplate)提供了对Redis的数据查询和操作功能。本文主要介绍基于RedisTemplate + lettuce方式对Redis进行查询和操作...
    99+
    2023-09-05
    redis spring boot java
  • 关于SpringBoot集成Lettuce连接Redis的方法和案例
    目录 使用SpringBoot集成Lettuce连接实例Springboot+Lettuce单连方式连接Redis单机/主备/Proxy集群示例。1、在applicatio...
    99+
    2023-05-17
    SpringBoot集成 SpringBoot集成Lettuce SpringBoo连接Redis
  • 怎么使用springBoot集成redis
    这篇文章将为大家详细讲解有关怎么使用springBoot集成redis,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。REmote DIctionary Server(Re...
    99+
    2022-10-18
  • SpringBoot集成如何使用Redis
    小编给大家分享一下SpringBoot集成如何使用Redis,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!SpringBoot集成使用redisJedis 是 Redis 官方推出的一款面向 Java 的客户端,提供了很多...
    99+
    2023-06-29
  • SpringBoot集成SSM、Dubbo、Redis、JSP的案例小结及思路讲解
    目录1.思路讲解2.案例分析2.1接口工程2.2服务提供者2.3服务消费者2.4启动测试!!!1.思路讲解 这个案例其实就是SpringBoot集成SSM、Dubbo、Redis、J...
    99+
    2022-11-12
  • SpringBoot集成Redis—使用RedisRepositories详解
    目录SpringBoot集成Redis 1.添加redis依赖2.在application.properties中添加redis配置信息3.SpringBoot启动类中添加...
    99+
    2022-11-13
  • SpringBoot集成Redis如何使用RedisRepositories
    这篇“SpringBoot集成Redis如何使用RedisRepositories”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这...
    99+
    2023-06-29
  • springBoot整合redis使用案例详解
    一、创建springboot项目(采用骨架方式) 创建完成; 我们分析下pom文件中内容: 所使用到的关键依赖: <!--springBoot集成redis-...
    99+
    2022-11-12
  • springboot集成redis的使用注解有哪些
    这篇文章给大家分享的是有关springboot集成redis的使用注解有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。redis简介:Redis是当前比较热门的NOSQL系统之一,它是一个开源的使用ANSI&...
    99+
    2023-06-29
  • 详解SpringBoot集成消息队列的案例应用
    目录背景方案规划统一设计集成Redis消息队列集成ActiveMQ消息队列使用示例背景 最近在对公司开发框架进行优化,框架内涉及到多处入库的日志记录,例如登录日志/操作日志/访问日志...
    99+
    2022-11-13
  • 【超详细】springboot + springdoc-openapi + knife4j 集成案例
    springdoc-openapi 简介 springdoc-openapijava库有助于使用 spring boot 项目自动生成 API 文档。 springdoc-openapi通过在运行时检查应用程序以根据 spring 配置、...
    99+
    2023-09-17
    java Powered by 金山文档
  • SpringBoot集成使用Redis及搭建过程
    目录SpringBoot集成使用redis搭建1.导入jar包2.配置连接redis3.添加配置类RedisConfig4.注入RedisTemplate5.测试和使用使用实例:Sp...
    99+
    2022-11-13
  • springboot集成redis并使用redis生成全局唯一索引ID
    部署redis Windows下搭建Reids本地集群,可参考https://www.jb51.net/article/242520.htm springboot集成 redis p...
    99+
    2022-11-13
  • SpringBoot集成Redis的思路详解
    目录SpringBoot集成Redis1、概述2、测试Redis3、自定义redisTemplateSpringBoot集成Redis 1、概述 Redis是什么? Redis(...
    99+
    2022-11-12
  • SpringBoot集成Redis的过程介绍
    本篇文章和大家了解一下SpringBoot集成Redis的过程介绍。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。Redis 介绍: Redis 服务Redis (REmote Dictionary Server) 是一个...
    99+
    2023-06-15
  • redis redisson 集合的使用案例(RList、Rset、RMap)
    redis redisson 集合操作 相关类及接口 Rlist:链表 public interface RList<V> extends List<V>...
    99+
    2022-11-12
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作