### Configure SOFABoot Services via XML Source: https://context7.com/sofastack/sofa-boot/llms.txt Demonstrates how to define and publish services using the SOFA XML namespace. It includes examples for JVM services, Bolt RPC bindings with custom timeouts, and direct service references. ```xml ``` -------------------------------- ### ServiceClient and ReferenceClient APIs Source: https://context7.com/sofastack/sofa-boot/llms.txt Provides examples of using ServiceClient and ReferenceClient for programmatic service publishing and dynamic reference creation at runtime. ```APIDOC ## ServiceClient and ReferenceClient APIs The programmatic API allows dynamic service registration and reference creation at runtime. Use `ServiceClient` to publish services and `ReferenceClient` to create service references dynamically. ### Publishing and Referencing Services Dynamically ```java import com.alipay.sofa.runtime.api.annotation.SofaClientFactory; import com.alipay.sofa.runtime.api.client.ReferenceClient; import com.alipay.sofa.runtime.api.client.ServiceClient; import com.alipay.sofa.runtime.api.client.param.ReferenceParam; import com.alipay.sofa.runtime.api.client.param.ServiceParam; import org.springframework.stereotype.Component; @Component public class DynamicServiceManager { @SofaClientFactory private ServiceClient serviceClient; @SofaClientFactory private ReferenceClient referenceClient; // Dynamically publish a service public void publishService(SampleService serviceImpl) { ServiceParam serviceParam = new ServiceParam(); serviceParam.setInterfaceType(SampleService.class); serviceParam.setInstance(serviceImpl); serviceParam.setUniqueId("dynamic"); serviceClient.service(serviceParam); } // Dynamically create a service reference public SampleService getServiceReference() { ReferenceParam referenceParam = new ReferenceParam<>(); referenceParam.setInterfaceType(SampleService.class); referenceParam.setUniqueId("dynamic"); return referenceClient.reference(referenceParam); } // Remove a published service (with delay for graceful shutdown) public void removeService() { serviceClient.removeService(SampleService.class, "dynamic", 5000); } } ``` ### API Methods - **`ServiceClient.service(ServiceParam)`**: Publishes a service dynamically. - **`ReferenceClient.reference(ReferenceParam)`**: Creates a dynamic reference to a service. - **`ServiceClient.removeService(Class interfaceType, String uniqueId, long delay)`**: Removes a published service after a specified delay. ``` -------------------------------- ### Configure SOFABoot Dependencies via Maven Source: https://context7.com/sofastack/sofa-boot/llms.txt This snippet demonstrates how to import the SOFABoot BOM and include necessary starters for core functionality, RPC, modular development, and actuator support in a Maven project. ```xml com.alipay.sofa sofaboot-dependencies 4.6.0 pom import com.alipay.sofa sofa-boot-starter com.alipay.sofa rpc-sofa-boot-starter com.alipay.sofa isle-sofa-boot-starter com.alipay.sofa actuator-sofa-boot-starter ``` -------------------------------- ### Implement SOFABoot Extension Points Source: https://context7.com/sofastack/sofa-boot/llms.txt Defines an extension point for plugin management and demonstrates how to contribute a plugin implementation. This pattern allows for modular functionality extension. ```xml Custom plugin implementation ``` -------------------------------- ### Configure SOFABoot Runtime and RPC via YAML Source: https://context7.com/sofastack/sofa-boot/llms.txt Provides a comprehensive configuration template for SOFABoot applications. It covers runtime settings, RPC protocol configurations (Bolt, REST, Triple), fault tolerance, and module ISLE settings. ```yaml spring: application: name: my-sofa-application sofa: boot: runtime: skipJvmReferenceHealthCheck: false disableJvmFirst: false jvmFilterEnable: true asyncInitExecutorCoreSize: 8 asyncInitExecutorMaxSize: 16 serviceCanBeDuplicate: false rpc: registryAddress: zookeeper://127.0.0.1:2181 boltPort: 12200 boltThreadPoolCoreSize: 20 boltThreadPoolMaxSize: 200 boltThreadPoolQueueSize: 0 restPort: 8341 restHostname: 0.0.0.0 restContextPath: / restThreadPoolMaxSize: 200 triplePort: 50051 tripleThreadPoolCoreSize: 20 tripleThreadPoolMaxSize: 200 aftRegulationEffective: true aftDegradeEffective: true aftTimeWindow: 10000 aftLeastWindowCount: 10 registries: local: local:// zk: zookeeper://zk1:2181,zk2:2181 isle: moduleStartUpParallel: true parallelRefreshPoolSizeFactor: 5.0 parallelRefreshTimeout: 60 allowBeanDefinitionOverriding: false publishEventToParent: false activeProfiles: - dev ignoreModules: - disabled-module switch: bean: runtimeAsyncInit: true management: endpoints: web: exposure: include: health,readiness,components,startup endpoint: health: show-details: always ``` -------------------------------- ### Query SOFABoot Readiness and Health Endpoints Source: https://context7.com/sofastack/sofa-boot/llms.txt Uses curl commands to check the application readiness, component health, and startup metrics. These endpoints are essential for traffic management in production environments. ```bash curl -X GET http://localhost:8080/actuator/readiness curl -X GET http://localhost:8080/actuator/components curl -X GET http://localhost:8080/actuator/startup ``` -------------------------------- ### Dynamic Service Management with ServiceClient and ReferenceClient Source: https://context7.com/sofastack/sofa-boot/llms.txt Shows how to programmatically publish, retrieve, and remove services at runtime using the SOFA runtime client APIs. This is useful for scenarios where services are not known at compile time. ```java import com.alipay.sofa.runtime.api.annotation.SofaClientFactory; import com.alipay.sofa.runtime.api.client.ReferenceClient; import com.alipay.sofa.runtime.api.client.ServiceClient; import com.alipay.sofa.runtime.api.client.param.ReferenceParam; import com.alipay.sofa.runtime.api.client.param.ServiceParam; import org.springframework.stereotype.Component; @Component public class DynamicServiceManager { @SofaClientFactory private ServiceClient serviceClient; @SofaClientFactory private ReferenceClient referenceClient; public void publishService(SampleService serviceImpl) { ServiceParam serviceParam = new ServiceParam(); serviceParam.setInterfaceType(SampleService.class); serviceParam.setInstance(serviceImpl); serviceParam.setUniqueId("dynamic"); serviceClient.service(serviceParam); } public SampleService getServiceReference() { ReferenceParam referenceParam = new ReferenceParam<>(); referenceParam.setInterfaceType(SampleService.class); referenceParam.setUniqueId("dynamic"); return referenceClient.reference(referenceParam); } public void removeService() { serviceClient.removeService(SampleService.class, "dynamic", 5000); } } ``` -------------------------------- ### Configure SOFABoot Module Metadata Source: https://context7.com/sofastack/sofa-boot/llms.txt Defines module identity, dependencies, and profiles using the sofa-module.properties file. This file must be placed in the module's resources directory. ```properties Module-Name=com.example.user-module Spring-Parent=com.example.core-module Require-Module=com.example.common-module,com.example.data-module Module-Profile=dev,prod ``` -------------------------------- ### Expose Services via SOFABoot JVM Binding Source: https://context7.com/sofastack/sofa-boot/llms.txt Configures a service bean and publishes it for other modules to consume using the SOFABoot JVM binding in XML configuration. ```xml ``` -------------------------------- ### @SofaAsyncInit Annotation Source: https://context7.com/sofastack/sofa-boot/llms.txt Explains the @SofaAsyncInit annotation for enabling asynchronous bean initialization to speed up application startup. ```APIDOC ## @SofaAsyncInit Annotation The `@SofaAsyncInit` annotation enables asynchronous bean initialization, accelerating application startup by parallelizing slow initialization tasks. The bean's init-method runs in a separate thread pool. ### Enabling Asynchronous Initialization ```java import com.alipay.sofa.runtime.api.annotation.SofaAsyncInit; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component @SofaAsyncInit public class SlowInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { // This runs asynchronously during startup Thread.sleep(5000); // Simulate slow initialization System.out.println("Slow bean initialized in thread: " + Thread.currentThread().getName()); } } ``` ### Global Configuration (application.properties) To enable async initialization globally and configure its thread pool: ```properties sofa.boot.switch.bean.runtimeAsyncInit=true sofa.boot.runtime.asyncInitExecutorCoreSize=8 sofa.boot.runtime.asyncInitExecutorMaxSize=16 ``` ``` -------------------------------- ### Manage Plugin Extensions with Java Source: https://context7.com/sofastack/sofa-boot/llms.txt Provides the Java descriptor and manager class to handle plugin contributions to extension points. Uses XMap annotations for XML mapping. ```java @XObject("plugin") public class PluginDescriptor { @XNode("@name") private String name; @XNode("@priority") private int priority; @XNode("description") private String description; } public class PluginManager { private List plugins = new ArrayList<>(); public void registerExtension(PluginDescriptor plugin) { plugins.add(plugin); plugins.sort(Comparator.comparingInt(PluginDescriptor::getPriority)); } } ``` -------------------------------- ### Asynchronous Bean Initialization with @SofaAsyncInit Source: https://context7.com/sofastack/sofa-boot/llms.txt Enables asynchronous bean initialization to speed up application startup. The bean's initialization logic runs in a separate thread pool, and global configuration can be adjusted via properties. ```java import com.alipay.sofa.runtime.api.annotation.SofaAsyncInit; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; @Component @SofaAsyncInit public class SlowInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { Thread.sleep(5000); System.out.println("Slow bean initialized in thread: " + Thread.currentThread().getName()); } } ``` -------------------------------- ### Implement ReadinessCheckCallback for Post-Readiness Logic Source: https://context7.com/sofastack/sofa-boot/llms.txt The ReadinessCheckCallback interface enables the execution of custom logic after all health checks have successfully passed. This is ideal for tasks like registering services with discovery servers or notifying load balancers. ```java import com.alipay.sofa.boot.actuator.health.ReadinessCheckCallback; import org.springframework.boot.actuate.health.Health; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class ServiceRegistrationCallback implements ReadinessCheckCallback { @Override public Health onHealthy(ApplicationContext applicationContext) { try { registerWithDiscovery(); notifyLoadBalancer(); return Health.up() .withDetail("registration", "completed") .withDetail("timestamp", System.currentTimeMillis()) .build(); } catch (Exception e) { return Health.down() .withDetail("registration", "failed") .withDetail("error", e.getMessage()) .build(); } } private void registerWithDiscovery() {} private void notifyLoadBalancer() {} } ``` -------------------------------- ### Expose Services with @SofaService Annotation Source: https://context7.com/sofastack/sofa-boot/llms.txt This snippet shows how to use the @SofaService annotation to publish Spring beans as SOFA services. It demonstrates local JVM services, Bolt RPC services with unique IDs, and services with multiple protocol bindings. ```java import com.alipay.sofa.runtime.api.annotation.SofaService; import com.alipay.sofa.runtime.api.annotation.SofaServiceBinding; import org.springframework.stereotype.Component; @Component @SofaService public class SampleServiceImpl implements SampleService { @Override public String sayHello(String name) { return "Hello, " + name; } } @Component @SofaService( interfaceType = SampleService.class, uniqueId = "boltService", bindings = @SofaServiceBinding(bindingType = "bolt") ) public class SampleServiceBoltImpl implements SampleService { @Override public String sayHello(String name) { return "Hello from Bolt, " + name; } } @Component @SofaService( bindings = { @SofaServiceBinding(bindingType = "jvm"), @SofaServiceBinding(bindingType = "bolt"), @SofaServiceBinding(bindingType = "rest") } ) public class MultiBindingServiceImpl implements MultiBindingService { @Override public String process(String input) { return "Processed: " + input; } } ``` -------------------------------- ### Define Module-Specific Spring Configuration Source: https://context7.com/sofastack/sofa-boot/llms.txt Demonstrates how to isolate Spring beans within a specific module using @Configuration and @ComponentScan. This ensures that module-specific beans do not leak into other modules. ```java package com.example.user; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ComponentScan; @Configuration @ComponentScan("com.example.user") public class UserModuleConfiguration { } ``` -------------------------------- ### Implement Custom HealthChecker for SOFABoot Source: https://context7.com/sofastack/sofa-boot/llms.txt The HealthChecker interface allows developers to define custom readiness checks. It provides methods to configure retry logic, timeouts, and strictness, ensuring the application is ready to receive traffic only when all checks pass. ```java import com.alipay.sofa.boot.actuator.health.HealthChecker; import org.springframework.boot.actuate.health.Health; import org.springframework.stereotype.Component; @Component public class DatabaseHealthChecker implements HealthChecker { @Override public Health isHealthy() { try { boolean dbConnected = checkDatabaseConnection(); if (dbConnected) { return Health.up() .withDetail("database", "connected") .withDetail("responseTime", "50ms") .build(); } else { return Health.down() .withDetail("database", "disconnected") .withDetail("error", "Connection refused") .build(); } } catch (Exception e) { return Health.down() .withDetail("error", e.getMessage()) .build(); } } @Override public String getComponentName() { return "databaseHealthChecker"; } @Override public int getRetryCount() { return 3; } @Override public long getRetryTimeInterval() { return 1000; } @Override public boolean isStrictCheck() { return true; } @Override public int getTimeout() { return 5000; } private boolean checkDatabaseConnection() { return true; } } ``` -------------------------------- ### Injecting Services with @SofaReference Source: https://context7.com/sofastack/sofa-boot/llms.txt Demonstrates how to use the @SofaReference annotation to inject services into Spring beans. It covers basic injection, unique ID filtering, specific binding configurations like Bolt, and direct URL connections. ```java import com.alipay.sofa.runtime.api.annotation.SofaReference; import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding; import org.springframework.stereotype.Component; @Component public class ServiceConsumer { @SofaReference private SampleService sampleService; @SofaReference(uniqueId = "boltService") private SampleService boltService; @SofaReference( jvmFirst = false, binding = @SofaReferenceBinding( bindingType = "bolt", timeout = 3000 ) ) private RemoteService remoteService; @SofaReference( binding = @SofaReferenceBinding( bindingType = "bolt", directUrl = "bolt://192.168.1.100:12200" ) ) private DirectService directService; public void doSomething() { String result = sampleService.sayHello("World"); System.out.println(result); } } ``` -------------------------------- ### @SofaReference Annotation Source: https://context7.com/sofastack/sofa-boot/llms.txt Demonstrates how to use the @SofaReference annotation to inject SOFA service references into Spring beans, supporting various configurations like unique IDs, binding types, and direct URLs. ```APIDOC ## @SofaReference Annotation The `@SofaReference` annotation injects a SOFA service reference into a Spring bean. It automatically creates a proxy that can invoke services locally (JVM) or remotely (RPC). By default, JVM invocation is preferred when available. ### Example Usage ```java import com.alipay.sofa.runtime.api.annotation.SofaReference; import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding; import org.springframework.stereotype.Component; @Component public class ServiceConsumer { // Simple reference (JVM first by default) @SofaReference private SampleService sampleService; // Reference with specific unique ID @SofaReference(uniqueId = "boltService") private SampleService boltService; // Reference with Bolt binding and timeout configuration @SofaReference( jvmFirst = false, binding = @SofaReferenceBinding( bindingType = "bolt", timeout = 3000 ) ) private RemoteService remoteService; // Reference with direct URL (bypasses registry) @SofaReference( binding = @SofaReferenceBinding( bindingType = "bolt", directUrl = "bolt://192.168.1.100:12200" ) ) private DirectService directService; public void doSomething() { String result = sampleService.sayHello("World"); System.out.println(result); } } ``` ### Configuration Options - `uniqueId`: Specifies a unique identifier for the service reference. - `jvmFirst`: If true, attempts to use local JVM invocation first. Defaults to true. - `binding`: Configures the service binding details. - `bindingType`: The type of binding (e.g., "bolt"). - `timeout`: The invocation timeout in milliseconds. - `directUrl`: A direct URL to the service provider, bypassing the registry. ``` -------------------------------- ### @SofaService Annotation Usage Source: https://context7.com/sofastack/sofa-boot/llms.txt The @SofaService annotation is used to publish a Spring bean as a SOFA service, allowing it to be consumed via various protocols. ```APIDOC ## @SofaService Annotation ### Description Publishes a Spring bean as a SOFA service. This allows the bean to be discovered and invoked via different protocols defined in the bindings. ### Parameters - **interfaceType** (Class) - Optional - The interface type of the service. - **uniqueId** (String) - Optional - A unique identifier to differentiate between multiple implementations of the same interface. - **bindings** (@SofaServiceBinding[]) - Optional - An array of binding configurations defining how the service is exposed (e.g., jvm, bolt, rest). ### Usage Example ```java @Component @SofaService( interfaceType = SampleService.class, uniqueId = "boltService", bindings = @SofaServiceBinding(bindingType = "bolt") ) public class SampleServiceBoltImpl implements SampleService { @Override public String sayHello(String name) { return "Hello from Bolt, " + name; } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.