You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot中结合Swagger/OpenAPI实现服务间客户端代码集成

Hey there! Since you're new to microservices and building with Spring Boot + OpenAPI, let's walk through exactly how to integrate the Blacklist Service client into your Token Service. This is a super common inter-service communication scenario, so here's a practical, step-by-step approach:

1. Generate the Blacklist Service Client from Your OpenAPI Spec

First, leverage the OpenAPI Generator to auto-generate the client code for Blacklist Service—this saves you from writing all the HTTP call boilerplate manually. You can use the Maven plugin (or Gradle equivalent) to hook this into your build process.

Add this to your Token Service's pom.xml:

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>6.6.0</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/openapi/blacklist-service.yaml</inputSpec>
                <generatorName>spring</generatorName>
                <configOptions>
                    <basePackage>com.yourcompany.blacklist.client</basePackage>
                    <apiPackage>com.yourcompany.blacklist.client.api</apiPackage>
                    <modelPackage>com.yourcompany.blacklist.client.model</modelPackage>
                    <useSpringBoot3>true</useSpringBoot3>
                    <feign>true</feign> <!-- Optional: Generate Feign client for simpler integration -->
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

Run mvn clean install—this will generate all the API interfaces, model classes, and client setup code you need.

2. Configure the Client in Token Service

Next, set up the client to connect to the Blacklist Service. If you generated a Feign client (via the <feign>true</feign> config), this is extra straightforward:

  1. Enable Feign clients in your Token Service main class:
    @SpringBootApplication
    @EnableFeignClients(basePackages = "com.yourcompany.blacklist.client.api")
    public class TokenServiceApplication {
        public static void main(String[] args) {
            SpringApplication.run(TokenServiceApplication.class, args);
        }
    }
    
  2. Add the Blacklist Service URL (or service name, if using service discovery) to application.properties:
    # If using direct URL
    blacklist.service.url=http://blacklist-service:8080
    # If using service discovery (e.g., Eureka), just use the service name in the client's base path
    

If you're using a standard RestTemplate instead, create a configuration bean to wire up the generated API client:

@Configuration
public class BlacklistClientConfig {

    @Value("${blacklist.service.url}")
    private String blacklistServiceBaseUrl;

    @Bean
    public BlacklistApi blacklistApi() {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(blacklistServiceBaseUrl);
        apiClient.setRestTemplate(new RestTemplate());
        return new BlacklistApi(apiClient);
    }
}
3. Integrate the Client into Your Token Service Logic

Now inject the generated client into your Token Service's business logic and use it to check the blacklist before issuing a token. Don't forget to handle potential failures (like the Blacklist Service being down)—microservices need to be resilient!

@Service
public class TokenService {

    private final BlacklistApi blacklistApi;

    // Constructor injection (preferred over @Autowired for testability)
    public TokenService(BlacklistApi blacklistApi) {
        this.blacklistApi = blacklistApi;
    }

    public String generateToken(String userId) {
        // Step 1: Check if user is blacklisted
        try {
            Boolean isBlacklisted = blacklistApi.checkUserBlacklist(userId);
            if (Boolean.TRUE.equals(isBlacklisted)) {
                throw new UnauthorizedException("User is blacklisted - cannot issue token");
            }
        } catch (ApiException e) {
            // Handle service errors: choose to fail closed (block token) or fail open (allow token) based on your security needs
            throw new ServiceUnavailableException("Failed to verify blacklist status", e);
        }

        // Step 2: Proceed with your existing token generation logic
        return Jwts.builder()
                .setSubject(userId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour expiry
                .signWith(SignatureAlgorithm.HS256, "your-secure-secret-key")
                .compact();
    }
}
4. Add Resilience (Optional but Critical for Production)

To handle cases where the Blacklist Service is unavailable, add a circuit breaker like Resilience4j to prevent cascading failures.

  1. Add the Resilience4j dependency to pom.xml:
    <dependency>
        <groupId>io.github.resilience4j</groupId>
        <artifactId>resilience4j-spring-boot3</artifactId>
        <version>2.1.0</version>
    </dependency>
    
  2. Update your service method to use the @CircuitBreaker annotation:
    @CircuitBreaker(name = "blacklistService", fallbackMethod = "blacklistCheckFallback")
    private Boolean checkUserBlacklist(String userId) throws ApiException {
        return blacklistApi.checkUserBlacklist(userId);
    }
    
    // Fallback method - define your failure behavior here
    private Boolean blacklistCheckFallback(String userId, Throwable throwable) {
        // Example: Fail closed (block token) if blacklist service is down
        throw new ServiceUnavailableException("Blacklist service unreachable - cannot verify user status");
    }
    

If you're using Spring Cloud, set up service discovery (e.g., Eureka) so your Token Service can automatically find the Blacklist Service without hardcoding URLs. Just add the Eureka client dependency and enable discovery in your app.


内容的提问来源于stack exchange,提问作者MrPavanayi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:33:20