当前位置: 首页 > article >正文

在Spring Cloud中将Redis共用到Common模块

前言

在分布式系统中,共用组件的设计可以极大地提升代码复用性和维护性。Spring Cloud中将Redis共用到一个公共模块(common模块)是一个常见的设计实践,这样可以让多个微服务共享相同的Redis配置和操作逻辑。本文将详细介绍如何在Spring Cloud中实现这一目标。

项目结构

首先,定义项目的结构:

spring-cloud-redis-common
│
├── common-module
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   │   └── com
│   │   │   │       └── example
│   │   │   │           └── common
│   │   │   │               ├── RedisConfig.java
│   │   │   │               ├── RedisService.java
│   │   │   │               └── model
│   │   │   │                   └── CacheItem.java
│   │   │   └── resources
│   │   │       └── application.properties
│   └── pom.xml
│
└── service-module
    ├── src
    │   ├── main
    │   │   ├── java
    │   │   │   └── com
    │   │   │       └── example
    │   │   │           └── service
    │   │   │               └── ServiceApplication.java
    │   │   └── resources
    │   │       └── application.properties
    └── pom.xml
​

Common模块的实现

1. 定义Redis配置

在 common-module中创建 RedisConfig.java,配置Redis连接:

package com.example.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }
}
​

2. 定义Redis操作服务

在 common-module中创建 RedisService.java,提供Redis操作方法:

package com.example.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }
}
​

3. 定义数据模型

在 common-module中创建 CacheItem.java,定义数据模型:

package com.example.common.model;

import java.io.Serializable;

public class CacheItem implements Serializable {
    private String id;
    private String value;

    // getters and setters
}
​

4. 配置文件

在 common-module的 resources目录下添加 application.properties

spring.redis.host=localhost
spring.redis.port=6379
​

5. 添加依赖

在 common-module的 pom.xml中添加Spring Data Redis依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
​

Service模块的实现

1. 添加依赖

在 service-module的 pom.xml中添加对 common-module的依赖:

<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>common-module</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>
​

2. 使用Common模块中的Redis服务

在 service-module中创建 ServiceApplication.java,使用 RedisService

package com.example.service;

import com.example.common.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServiceApplication implements CommandLineRunner {

    @Autowired
    private RedisService redisService;

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

    @Override
    public void run(String... args) throws Exception {
        redisService.set("testKey", "testValue", 1, TimeUnit.HOURS);
        System.out.println("Stored value: " + redisService.get("testKey"));
    }
}
​

3. 配置文件

在 service-module的 resources目录下添加 application.properties,以覆盖common模块中的配置:

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

http://www.kler.cn/a/534130.html

相关文章:

  • Agentic Automation:基于Agent的企业认知架构重构与数字化转型跃迁---我的AI经典战例
  • 四.4 Redis 五大数据类型/结构的详细说明/详细使用( zset 有序集合数据类型详解和使用)
  • 中国通信企业协会 通信网络安全服务能力评定 风险评估二级要求准则
  • k8m 是一款轻量级、跨平台的 Kubernetes 仪表板
  • 视频融合平台EasyCVR无人机场景视频压缩及录像方案
  • 解锁.NET Fiddle:在线编程的神奇之旅
  • Redis有哪些常用应用场景?
  • Spring MVC ONE
  • WordPress自动SEO文章生成器——一款基于AI技术的智能插件,能够自动生成高质量、SEO优化的文章,并提供强大的内容采集与优化功能。
  • zyNo.20
  • Got socket exception during request. It might be caused by SSL misconfiguration
  • 哪些专业跟FPGA有关?
  • 基于SpringBoot的体检预约管理系统
  • 5.【BUUCTF】[BJDCTF2020]Easy MD5及知识点
  • PyQt4学习笔记4】窗口布局 和 QSplitter
  • JAVAweb学习日记(九) MySQL-事务索引
  • 低代码提升交付效率的公式计算
  • 响应式编程_05 Project Reactor 框架
  • 永久免费语音服务!微软 Azure 注册实操,零成本实现TTS自由
  • Page Assist实现deepseek离线部署的在线搜索功能
  • Mac 基于Ollama 本地部署DeepSeek离线模型
  • MyBatis Plus 输出完整 SQL(带参数)的 3 种方案
  • Boosting 框架
  • 硬件工程师思考笔记02-器件的隐秘角落:磁珠与电阻噪声
  • 堆的实现——堆的应用(堆排序)
  • CTFSHOW-WEB入门-PHP特性89-100