Springboot集成Redis操作缓存-06

Redis简介

Redis(Remote Dictionary Server),即远程字典服务,是一个开源的、使用ANSI C语言编写的、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

功能特点

  1. 数据结构丰富:Redis支持多种数据结构,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集等丰富的操作,且这些操作都是原子性的。
  2. 高性能:Redis将数据存储在内存中,因此其读写速度非常快。根据官方数据,Redis可以轻松支持超过10万次QPS(每秒查询率)的读写频率。
  3. 持久化:虽然Redis主要将数据存储在内存中,但它也提供了持久化的功能。Redis可以周期性地将更新的数据写入磁盘,或将修改操作写入追加的记录文件,以确保数据的持久性。
  4. 主从同步和复制:Redis支持主从同步,数据可以从主服务器向任意数量的从服务器上同步。从服务器可以是关联其他从服务器的主服务器,这使得Redis可执行单层树复制。
  5. 哨兵(Sentinel)和集群(Cluster):Sentinel可以管理多个Redis服务器,提供监控、提醒以及自动的故障转移功能。Redis Cluster则允许将数据分布在多个Redis节点上,以实现横向扩展和负载均衡。
  6. 分布式锁:Redis还可以用作分布式锁,以确保在分布式系统中对共享资源的访问是同步的。
  7. 发布/订阅机制:Redis完全实现了发布/订阅机制,允许从数据库在任何地方同步树时,订阅一个频道并接收主服务器完整的消息发布记录。

应用场景

如缓存服务、消息队列、分布式锁等。由于其高性能和丰富的功能,Redis已经成为许多主流架构中不可或缺的一部分。

关于Redis的安装和使用,可以根据不同的操作系统和需求选择相应的方法。例如,在Windows系统中,可以通过解压并双击redis-server.exe和redis-cli.exe来启动服务器和命令窗口。在Linux系统中,则可以按照详细的安装部署教程进行安装和配置。同时,Redis也提供了丰富的命令和API,以满足不同的使用需求。

Redis安装

笔者是在Macos系统下采用HomeBrew进行的安装

安装

bash 复制代码
brew install redis

启动

  • brew启动
bash 复制代码
brew services list
brew services start redis
brew services stop redis
ps -ef | grep redis
  • redis命令启动
bash 复制代码
# 启动
redis-server

# 客户端工具
redis-cli

# 设置密码
CONFIG SET requirepass YOUR_PASSWORD
auth YOUR_PASSWORD

springboot-redis模块

模块工程结构

pom.xml

依赖版本可参考 springbootSeries 模块中pom.xml文件中的版本定义

xml 复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>

application.properties配置

shell 复制代码
spring.profiles.active = dev
spring.application.name=springbootRedis
server.port=18087

spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name}

spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=

SpringbootApplication启动类

添加 @EnableDiscoveryClient 注解

java 复制代码
@Slf4j
@SpringBootApplication(scanBasePackages = {"com.korgs",  "cn.hutool.extra.spring"})
@Configuration
@EnableConfigurationProperties
@ServletComponentScan
@RestController
@EnableDiscoveryClient
public class SpringbootRedisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootRedisApplication.class, args);
	}

	@GetMapping("/helloworld")
	public BaseResponse helloWorld(){
		log.info(LogGenerator.trackLog()
				+ "msg="+ "I am busy to handle this request.");
		return BaseResponse.success("hello world");
	}
}

java-redis实现

Redis bean实现

在使用时有两个模板配置,Redis适用于需要持久化、复杂数据结构和高性能的场景,而Cache Manager适用于简单的缓存需求,部署和管理相对简单。具体使用哪种方案应根据实际需求和场景来决定。

java 复制代码
@Configuration
public class RedisConfig {

    @Bean
    RedisConnectionFactory connectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    RedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer( new JdkSerializationRedisSerializer());
        return template;
    }

    @Bean
    StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

RedisController实现

java 复制代码
@Slf4j
@RestController
@RequestMapping("/api/load")
public class RedisController {

    //Pushing an item to a List using [Reactive]RedisTemplate
    @Resource(name="redisTemplate")
    private ListOperations<String, String> listOps;

    //String-focused Convenience Classes
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/v1/listOperator")
    public BaseResponse<String> listOperator(String uuid, String url){
        log.info(LogGenerator.trackLog() + uuid + ":" + listOps.size(uuid));
        String cache = listOps.index(uuid, 0);
        if (StrUtil.isEmpty(cache)){
            listOps.leftPush(uuid, url);
            return BaseResponse.success(uuid + ":" + url);
        }

        listOps.leftPush(uuid, url);
        return BaseResponse.success(uuid + ":" + cache);
    }

    @GetMapping("/v1/stringOperator")
    public BaseResponse<String> stringOperator(String uuid, String url){
        String cache = redisTemplate.opsForValue().get(uuid);
        log.info(LogGenerator.trackLog() + uuid + ":" + cache);
        if (StrUtil.isEmpty(cache)){
            redisTemplate.opsForValue().set(uuid, url);
            return BaseResponse.success(uuid + ":" + url);
        }
        redisTemplate.opsForValue().set(uuid, url);
        return BaseResponse.success(uuid + ":" + cache);
    }

    //how to use the RedisCallback interface
    public void useCallback() {
        redisTemplate.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                Long size = connection.dbSize();
                // Can cast to StringRedisConnection if using a StringRedisTemplate
                ((StringRedisConnection)connection).set("key", "value");
                return size;
            }
        });
    }
}

源码下载

涉及模块:

  • springboot-redis:18087

源码下载:

源码运行方法:

相关推荐
bjzhang7514 分钟前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang19 分钟前
Spring Boot 入门面试五道题
spring boot
小菜yh20 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
问道飞鱼44 分钟前
分布式中间件-Pika一个高效的分布式缓存组件
分布式·缓存·中间件
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱2 小时前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
serve the people2 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
小安运维日记3 小时前
Linux云计算 |【第四阶段】NOSQL-DAY1
linux·运维·redis·sql·云计算·nosql
罗政7 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
码农郁郁久居人下8 小时前
Redis的配置与优化
数据库·redis·缓存