Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@
<evictor.version>1.0.0</evictor.version>
<bouncycastle-bcprov-jdk18on.version>1.83</bouncycastle-bcprov-jdk18on.version>
<jspecify.enabled>true</jspecify.enabled>
<spring-grpc.version>1.0.2</spring-grpc.version>
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should all be managed by spring boot. Since this won't be merged until summer time (when we start on our new minor), this will be based on boot 4.2, but in the meantime you can start with 4.1 and spring grpc 1.1

<grpc.version>1.79.0</grpc.version>
</properties>
<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,32 @@ public class LoadBalancerClientsProperties extends LoadBalancerProperties {

private final Map<String, LoadBalancerProperties> clients = new HashMap<>();

private GrpcClient grpcClient = new GrpcClient();

public Map<String, LoadBalancerProperties> getClients() {
return this.clients;
}

public GrpcClient getGrpcClient() {
return grpcClient;
}

public void setGrpcClient(GrpcClient grpcClient) {
this.grpcClient = grpcClient;
}

public static class GrpcClient {

private boolean enabled = false;

public boolean isEnabled() {
return enabled;
}

public void setEnabled(boolean enabled) {
this.enabled = enabled;
}

}

}
12 changes: 12 additions & 0 deletions spring-cloud-loadbalancer/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,18 @@
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.grpc</groupId>
<artifactId>spring-grpc-core</artifactId>
<version>${spring-grpc.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright 2012-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.loadbalancer.annotation.grpc;

import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author KouShenhai(laokou)
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
public @interface GrpcClient {

/**
* Synonym for name (the name of the grpc client).
*
* @see #name()
* @return the name of the load balancer grpc client
*/
@AliasFor("name")
String value() default "";

/**
* The name of the load balancer grpc client, uniquely identifying a set of client
* resources, including a load balancer.
* @return the name of the load balancer grpc client
*/
@AliasFor("value")
String name() default "";

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2012-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.loadbalancer.annotation.grpc;

import org.jspecify.annotations.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.grpc.client.GrpcClientFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* @author KouShenhai(laokou)
*/
public class GrpcClientBeanPostProcessor implements BeanPostProcessor {

private final GrpcClientFactory grpcClientFactory;

public GrpcClientBeanPostProcessor(GrpcClientFactory grpcClientFactory) {
this.grpcClientFactory = grpcClientFactory;
}

@Override
public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName)
throws BeansException {
Class<?> clazz = bean.getClass();
do {
setFields(bean, clazz);
setMethods(bean, clazz);
clazz = clazz.getSuperclass();
}
while (!ObjectUtils.isEmpty(clazz));
return bean;
}

private void setFields(Object bean, Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
GrpcClient grpcClient = AnnotationUtils.findAnnotation(field, GrpcClient.class);
if (!ObjectUtils.isEmpty(grpcClient)) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, getClient(field.getType(), grpcClient));
}
}
}

private void setMethods(Object bean, Class<?> clazz) {
for (Method method : clazz.getDeclaredMethods()) {
GrpcClient grpcClient = AnnotationUtils.findAnnotation(method, GrpcClient.class);
if (!ObjectUtils.isEmpty(grpcClient)) {
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, bean, getClient(method.getParameterTypes()[0], grpcClient));
}
}
}

private <T> T getClient(Class<T> type, @NonNull GrpcClient grpcClient) {
String target = String.format("discovery://%s", getClientName(grpcClient));
return grpcClientFactory.getClient(target, type, null);
}

private String getClientName(GrpcClient grpcClient) {
String value = grpcClient.value();
if (!StringUtils.hasText(value)) {
value = grpcClient.name();
}
if (StringUtils.hasText(value)) {
return value;
}
throw new IllegalStateException("Either 'name' or 'value' must be provided in @GrpcClient");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,37 @@

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;

import io.grpc.netty.NettyChannelBuilder;
import org.jspecify.annotations.NonNull;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClientsProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalancerEagerLoadProperties;
import org.springframework.cloud.client.loadbalancer.reactive.LoadBalancerBeanPostProcessorAutoConfiguration;
import org.springframework.cloud.client.loadbalancer.reactive.ReactorLoadBalancerClientAutoConfiguration;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClientSpecification;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.annotation.grpc.GrpcClientBeanPostProcessor;
import org.springframework.cloud.loadbalancer.aot.LoadBalancerChildContextInitializer;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.cloud.loadbalancer.support.LoadBalancerEagerContextInitializer;
import org.springframework.cloud.loadbalancer.support.grpc.DiscoveryGrpcChannelFactory;
import org.springframework.cloud.loadbalancer.support.grpc.DiscoveryNameResolverProvider;
import org.springframework.cloud.loadbalancer.support.grpc.DiscoveryNameResolverRegister;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.grpc.client.ClientInterceptorsConfigurer;
import org.springframework.grpc.client.GrpcChannelBuilderCustomizer;
import org.springframework.grpc.client.GrpcClientFactory;

/**
* @author Spencer Gibb
Expand Down Expand Up @@ -77,4 +89,37 @@ static LoadBalancerChildContextInitializer loadBalancerChildContextInitializer(
return new LoadBalancerChildContextInitializer(loadBalancerClientFactory, parentContext);
}

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DiscoveryClient.class, GrpcClientFactory.class, ClientInterceptorsConfigurer.class,
ExecutorService.class })
@ConditionalOnProperty(prefix = "spring.cloud.loadbalancer.grpc-client", name = "enabled", havingValue = "true",
matchIfMissing = true)
static class GrpcClientConfiguration {

@Bean
DiscoveryNameResolverProvider discoveryNameResolverProvider(DiscoveryClient discoveryClient,
ExecutorService executorService) {
return new DiscoveryNameResolverProvider(discoveryClient, executorService);
}

@Bean
DiscoveryNameResolverRegister discoveryNameResolverRegister(
DiscoveryNameResolverProvider discoveryNameResolverProvider) {
return new DiscoveryNameResolverRegister(discoveryNameResolverProvider);
}

@Bean
GrpcClientBeanPostProcessor grpcClientBeanPostProcessor(GrpcClientFactory grpcClientFactory) {
return new GrpcClientBeanPostProcessor(grpcClientFactory);
}

@Bean
DiscoveryGrpcChannelFactory discoveryGrpcChannelFactory(
List<GrpcChannelBuilderCustomizer<@NonNull NettyChannelBuilder>> globalCustomizers,
ClientInterceptorsConfigurer interceptorsConfigurer) {
return new DiscoveryGrpcChannelFactory(globalCustomizers, interceptorsConfigurer);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright 2012-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.loadbalancer.support.grpc;

import io.grpc.ChannelCredentials;
import io.grpc.netty.NettyChannelBuilder;
import org.jspecify.annotations.NonNull;
import org.springframework.grpc.client.ClientInterceptorsConfigurer;
import org.springframework.grpc.client.GrpcChannelBuilderCustomizer;
import org.springframework.grpc.client.NettyGrpcChannelFactory;

import java.util.List;

/**
* Discovery Grpc ChannelFactory.
*
* @author KouShenhai(laokou)
*/
public class DiscoveryGrpcChannelFactory extends NettyGrpcChannelFactory {

/**
* 构建通道工厂实例.
* @param globalCustomizers 要应用于所有已创建频道的全局自定义设置
* @param interceptorsConfigurer 配置已创建通道上的客户端拦截器
*/
public DiscoveryGrpcChannelFactory(
List<GrpcChannelBuilderCustomizer<@NonNull NettyChannelBuilder>> globalCustomizers,
ClientInterceptorsConfigurer interceptorsConfigurer) {
super(globalCustomizers, interceptorsConfigurer);
setVirtualTargets((p) -> p.substring(12));
}

@Override
public boolean supports(String target) {
return target.startsWith("discovery:");
}

@NonNull
@Override
protected NettyChannelBuilder newChannelBuilder(@NonNull String target, @NonNull ChannelCredentials credentials) {
return NettyChannelBuilder.forTarget(String.format("discovery://%s", target), credentials);
}

}
Loading