轻量 · 零侵入 · 支持 HTTP/Redis/RabbitMQ/WebSocket 直连与注册中心
Invoker RPC 是一款面向 Spring Boot 3.0+ / JDK 17+ 的简易 RPC
框架,设计目标为零侵入、多协议、易扩展。只需在启动类添加 @EnableRemoteDiscoveryClient,在接口上标注
@RemoteClient / @RemoteRedisClient 等注解,即可无缝切换 HTTP、Redis、RabbitMQ、WebSocket
调用,并集成 Nacos、Eureka、Consul、Zookeeper 注册中心,也支持直连模式。老项目改造极简,几乎不修改业务代码。
@RemoteCloudClient@RemoteClient @RemoteRedisClient@RemoteAmqpClient@RemoteWebSocketClientEncoder/Decoder。通过 spring-invoker-dependencies 统一管理版本(推荐):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.i360day</groupId>
<artifactId>spring-invoker-dependencies</artifactId>
<version>4.0.0/3.0.4/2.0.8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
按需引入 starter(例如 HTTP+注册中心):
<dependency>
<groupId>com.i360day</groupId>
<artifactId>spring-cloud-starter-invoker</artifactId>
</dependency>
其他模式 starter:
| 依赖 | 描述 |
|---|---|
| spring-boot-starter-invoker | 基础 HTTP 直连(无注册中心) |
| spring-boot-starter-redis-invoker | Redis 远程调用 |
| spring-boot-starter-amqp-invoker | RabbitMQ 远程调用 |
| spring-boot-starter-websocket-invoker | WebSocket 远程调用 |
| spring-cloud-starter-invoker | 微服务注册中心版(Eureka / Nacos / Consul / Zookeeper) |
spring:
invoker:
# 序列化方式:json 或 jdk (默认json)
serializable: json
# 请求客户端配置
request:
client: httpClient # 或 okHttp
maxConnections: 100
timeToLive: 30000 # 最大空闲时间(ms)
connectionRequestTimeout: 15000
connectTimeout: 20000
readTimeout: 15000
# 全局客户端配置(可被接口注解覆盖)
global-client:
fallback: com.xxx.TestFallback
fallbackFactory: com.xxx.FallbackFactory
client-user: invoker-user
client-password: invoker-password
# 全局服务端配置
global-server:
server-user: invoker-user
server-password: invoker-password
# WebSocket 专属配置
webSocket:
endpoint: /websocket-invoker
server-user-name: invoker-username
server-password: 123456
# 线程池配置
thread-pool:
core-pool-size: 10
queue-capacity: 100
keep-alive-seconds: 600
thread-name-prefix: invoker-thread-pool
rejected-execution-handler: java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy
在 Spring Boot 启动类添加 @EnableRemoteDiscoveryClient(即使不使用注册中心也需要此注解启用核心功能)
@SpringBootApplication
@EnableRemoteDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
创建接口,并使用相应注解标记调用模式。支持泛型、异步、数组等复杂参数。
@RemoteClient(
address = "http://127.0.0.1:9092/invoker-service",
fallbackFactory = DemoServiceFallback.class
)
public interface DemoService {
String sayHello(String name);
@Async // 异步调用
void noReturn(String msg);
@RemoteDisable // 禁用此方法调用
String deprecatedMethod();
}
@RemoteRedisClient(address = "redis://127.0.0.1:6379/invoker-service")
public interface RedisCounterService {
Long increment(String key);
}
@RemoteAmqpClient(address = "amqp://127.0.0.1:5672,amqp://node2:5672") // 集群逗号分隔
public interface AmqpMailService {
void send(String payload);
}
@RemoteWebSocketClient(address = "ws://127.0.0.1:9092/invoker-service")
public interface WsNotifyService {
String notify(String msg);
}
@RemoteModule(address = "${service.demo.address:http://localhost:9092/invoker}")
public interface DemoModule {
// 可定义默认方法或留空
}
@RemoteClient(fallback = DemoFallback.class)
public interface DemoService extends DemoModule {
String hello();
}
服务端只需实现上述接口,并注册为 Spring Bean(如 @Service),框架自动将其暴露为远程服务。
@Service
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
// ... 其他方法
}
在 Controller 或 Service 中直接 @Autowired 接口:
@RestController
public class TestController {
@Autowired
private DemoService demoService; // HTTP直连
@Autowired
private RedisCounterService redisCounter; // Redis模式
@Autowired
private AmqpMailService amqpMail; // RabbitMQ模式
@GetMapping("/test")
public String test() {
return demoService.sayHello("Invoker");
}
}
全局或接口级别配置 Hystrix 属性。例如在 application.yml 中:
spring:
invoker:
hystrix:
enabled: true
command:
circuitBreakerEnabled: true
circuitBreakerErrorThresholdPercentage: 90
executionTimeoutInMilliseconds: 3000
fallbackEnabled: true
thread:
coreSize: 10
maximumSize: 20
maxQueueSize: 5
接口级别可通过注解 @RemoteClient(fallbackFactory = Xxx.class) 指定降级工厂。
实现 Encoder / Decoder 接口,并在 @RemoteClient 上指定:
//@RemoteClient(decoder = JsonDecoder.class, encoder = JsonEncoder.class)
@RemoteClient(decoder = JavaDecoder.class, encoder = JavaEncoder.class)
public interface CustomService { ... }
实现 InvokerRequestInterceptor 添加全局 Header(如 OAuth2 token):
@Bean
public InvokerRequestInterceptor authInterceptor() {
return requestTemplate ->
requestTemplate.addHeader("Authorization", "Bearer xxx");
}
若服务端配置了 server-user/password,客户端必须匹配
@RemoteModule(clientUser/clientPassword)。某些接口可加 @RemoteIgnoreSecurity 忽略认证。
@RemoteResponseBody(deserialize = TestVo.class) // 指定反序列化目标
<T> T testGeneric(List<?> wildcard, @RemoteRequestParam(serialize = HttpStatus.class) Enum<?> status);
只需引入 spring-boot-starter-invoker,并在 @RemoteClient 中写死 address 即可。
| 模块 | 说明 |
|---|---|
| spring-boot-invoker-annotations | 核心注解(@RemoteClient, @EnableRemoteDiscoveryClient ...) |
| spring-boot-invoker-core | 核心实现、代理、序列化 |
| spring-boot-invoker-hystrix | 熔断集成 |
| spring-boot-starter-invoker | Spring Boot 自动配置(无注册中心) |
| spring-boot-starter-redis-invoker | Redis 调用支持 |
| spring-boot-starter-amqp-invoker | RabbitMQ 调用支持 |
| spring-boot-starter-websocket-invoker | WebSocket 调用支持 |
| spring-cloud-starter-invoker | Spring Cloud 注册中心集成 (loadbalancer) |
| spring-invoker-dependencies | 依赖版本管理 BOM |
服务提供方:
@Service
public class UserService implements UserServiceFacade {
public User findById(Long id) { return ...; }
}
消费方接口:
@RemoteCloudClient(name = "user-service", path = "/user-server") // 从注册中心发现 "user-service"
public interface UserServiceFacade {
User findById(Long id);
}
消费方注入即可。
@RemoteClient(address = "http://api.example.com/rpc")
public interface ExternalApi { ... }
@Bean
InvokerRequestInterceptor signInterceptor() {
return request -> request.addHeader("X-Sign", computeSign());
}
@RemoteRedisClient(address = "redis://redis-cluster:6379")
public interface RedisCounter {
Long incr(String key);
}
// 服务端实现(任何 Spring Bean 实现该接口即可)
@Service
public class RedisCounterImpl implements RedisCounter {
@Autowired private StringRedisTemplate template;
public Long incr(String key) {
return template.opsForValue().increment(key);
}
}
Targeter:自定义代理生成逻辑RemoteInvocationExecutor:服务端请求执行器InvokerRequestInterceptor:客户端请求拦截Encoder/Decoder:自定义序列化RemoteInvocationConverterFactory:RemoteInvocation序列化spring-cloud-invoker-sample。
Invoker RPC · 简单 · 强大 · 多合一远程调用