Since Dubbo 3.3, the Triple protocol reuses the existing HTTP stack to fully support RESTful service exports. Without the need for generic or gateway protocol conversion, users can directly access backend Triple protocol services via HTTP in a decentralized manner. Additionally, it offers extensive annotation and SPI extension support for advanced REST usage, such as path customization, output format customization, and exception handling. Key features include:
Let’s explore Triple Rest with a simple example. You can directly download the existing sample project to get started quickly. Assume you have Java, Maven, and Git installed.
# Get the sample code
git clone --depth=1 https://github.com/apache/dubbo-samples.git
cd dubbo-samples/2-advanced/dubbo-samples-triple-rest/dubbo-samples-triple-rest-basic
# Run directly
mvn spring-boot:run
# Or package and run
mvn clean package -DskipTests
java -jar target/dubbo-samples-triple-rest-basic-1.0.0-SNAPSHOT.jar
Alternatively, you can import the project into your IDE and directly execute org.apache.dubbo.rest.demo.BasicRestApplication#main
to run it. You can also debug by setting
breakpoints to deeply understand the principles.
// Service Interface
package org.apache.dubbo.rest.demo;
import org.apache.dubbo.remoting.http12.rest.Mapping;
import org.apache.dubbo.remoting.http12.rest.Param;
public interface DemoService {
String hello(String name);
@Mapping(path = "/hi", method = HttpMethods.POST)
String hello(User user, @Param(value = "c", type = ParamType.Header) int count);
}
// Service Implementation
@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String hello(String name) {
return "Hello " + name;
}
@Override
public String hello(User user, int count) {
return "Hello " + user.getTitle() + ". " + user.getName() + ", " + count;
}
}
// Model
@Data
public class User {
private String title;
private String name;
}
curl -v "http://127.0.0.1:8081/org.apache.dubbo.rest.demo.DemoService/hello?name=world"
# Output:
#> GET /org.apache.dubbo.rest.demo.DemoService/hello?name=world HTTP/1.1
#> Host: 127.0.0.1:8081
#> User-Agent: curl/8.7.1
#> Accept: */*
#>
#* Request completely sent off
#< HTTP/1.1 200 OK
#< content-type: application/json
#< alt-svc: h2=":8081"
#< content-length: 13
#<
#"Hello world"
Explanation:
You see the output "Hello world"
. The quotes are because the default content-type is application/json
. This example demonstrates how Triple exports services
to the /{serviceInterface}/{methodName}
path by default and supports passing parameters via URL.
curl -v -H "c: 3" -d 'name=Yang' "http://127.0.0.1:8081/org.apache.dubbo.rest.demo.DemoService/hi.txt?title=Mr"
# Output:
#> POST /org.apache.dubbo.rest.demo.DemoService/hi.txt?title=Mr HTTP/1.1
#> Host: 127.0.0.1:8081
#> User-Agent: curl/8.7.1
#> Accept: */*
#> c: 3
#> Content-Length: 9
#> Content-Type: application/x-www-form-urlencoded
#>
#* upload completely sent off: 9 bytes
#< HTTP/1.1 200 OK
#< content-type: text/plain
#< alt-svc: h2=":8081"
#< content-length: 17
#<
#Hello Mr. Yang, 3
Explanation:
The output "Hello Mr. Yang, 3"
has no quotes because the .txt
suffix was specified to request text/plain
output. This example shows how to customize paths
using the Mapping
annotation, customize parameter sources with the Param
annotation, and pass parameters via post body or URL. For more details, see
the Basic Usage Guide
Enable debug logging to understand the rest startup and request response process:
logging:
level:
"org.apache.dubbo.rpc.protocol.tri": debug
"org.apache.dubbo.remoting": debug
Once enabled, you can observe the Rest mapping registration and request process:
# Register mapping
DEBUG o.a.d.r.p.t.TripleProtocol : [DUBBO] Register triple grpc mapping: 'org.apache.dubbo.rest.demo.DemoService' -> invoker[tri://192.168.2.216:8081/org.apache.dubbo.rest.demo.DemoService]
INFO .r.p.t.r.m.DefaultRequestMappingRegistry : [DUBBO] BasicRequestMappingResolver resolving rest mappings for ServiceMeta{interface=org.apache.dubbo.rest.demo.DemoService, service=DemoServiceImpl@2a8f6e6} at url [tri://192.168.2.216:8081/org.apache.dubbo.rest.demo.DemoService]
DEBUG .r.p.t.r.m.DefaultRequestMappingRegistry : [DUBBO] Register rest mapping: '/org.apache.dubbo.rest.demo.DemoService/hi' -> mapping=RequestMapping{name='DemoServiceImpl#hello', path=PathCondition{paths=[org.apache.dubbo.rest.demo.DemoService/hi]}, methods=MethodsCondition{methods=[POST]}}, method=MethodMeta{method=org.apache.dubbo.rest.demo.DemoService.hello(User, int), service=DemoServiceImpl@2a8f6e6}
DEBUG .r.p.t.r.m.DefaultRequestMappingRegistry : [DUBBO] Register rest mapping: '/org.apache.dubbo.rest.demo.DemoService/hello' -> mapping=RequestMapping{name='DemoServiceImpl#hello~S', path=PathCondition{paths=[org.apache.dubbo.rest.demo.DemoService/hello]}}, method=MethodMeta{method=org.apache.dubbo.rest.demo.DemoService.hello(String), service=DemoServiceImpl@2a8f6e6}
INFO .r.p.t.r.m.DefaultRequestMappingRegistry : [DUBBO] Registered 2 REST mappings for service [DemoServiceImpl@44627686] at url [tri://192.168.2.216:8081/org.apache.dubbo.rest.demo.DemoService] in 11ms
# 请求响应
DEBUG .a.d.r.p.t.r.m.RestRequestHandlerMapping : [DUBBO] Received http request: DefaultHttpRequest{method='POST', uri='/org.apache.dubbo.rest.demo.DemoService/hi.txt?title=Mr', contentType='application/x-www-form-urlencoded'}
DEBUG .r.p.t.r.m.DefaultRequestMappingRegistry : [DUBBO] Matched rest mapping=RequestMapping{name='DemoServiceImpl#hello', path=PathCondition{paths=[/org.apache.dubbo.rest.demo.DemoService/hi]}, methods=MethodsCondition{methods=[POST]}}, method=MethodMeta{method=org.apache.dubbo.rest.demo.DemoService.hello(User, int), service=DemoServiceImpl@2a8f6e6}
DEBUG .a.d.r.p.t.r.m.RestRequestHandlerMapping : [DUBBO] Content-type negotiate result: request='application/x-www-form-urlencoded', response='text/plain'
DEBUG .d.r.h.AbstractServerHttpChannelObserver : [DUBBO] Http response body is: '"Hello Mr. Yang, 3"'
DEBUG .d.r.h.AbstractServerHttpChannelObserver : [DUBBO] Http response headers sent: {:status=[200], content-type=[text/plain], alt-svc=[h2=":8081"], content-length=[17]}
The Triple protocol is compatible with both SpringMVC and JAX-RS mapping methods. For more information, refer to:
You can also customize path mapping by implementing the SPI org.apache.dubbo.rpc.protocol.tri.rest.mapping.RequestMappingResolver
.
books
: A string constant matching a fixed segment.?
: Matches a single character.*
: Matches zero or more characters within a path segment.**
: Matches zero or more path segments until the end of the path.{spring}
: Matches a path segment and captures it as a variable named “spring.”{spring:[a-z]+}
: Uses a regular expression [a-z]+
to match a path segment and captures it as a variable named “spring.”{*spring}
: Matches zero or more path segments until the end of the path and captures them as a variable named “spring.” {*}
without a variable name indicates that no
capturing is done.
/pages/t?st.html
: Matches /pages/test.html
and /pages/tXst.html
, but not /pages/toast.html
./resources/*.png
: Matches all .png
files in the resources
directory.com/**/test.jsp
: Matches all test.jsp
files under the com
path.org/springframework/**/*.jsp
: Matches all .jsp
files under the org/springframework
path./resources/**
: Matches all files under the /resources/
path, including /resources/image.png
and /resources/css/spring.css
./resources/{*path}
: Matches all files under /resources/
as well as /resources
itself, capturing the relative path as the variable “path.” For example,
/resources/image.png
would map to “path” → “/image.png”, and /resources/css/spring.css
would map to “path” → “/css/spring.css”./resources/{filename:\\w+}.dat
: Matches /resources/spring.dat
and assigns the value “spring” to the filename
variable./{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}
: Matches /example-2.1.5.html
, with name
as example
, version
as 2.1.5
, and ext
as .html
.Tip: If you do not want the regular expression to span multiple segments, use {name:[^/]+}
.
The detailed matching logic is implemented in the following code: DefaultRequestMappingRegistry.java, RequestMapping.java.
PathUtils.normalize
to remove indirect paths such as /one/../
or /one/./
, ensuring the path starts with /
.serviceGroup
and serviceVersion
match./
if trailing slash matching is enabled.~
, retry with method signature matching enabled.null
.Unlike Spring, which raises an error and prevents startup when paths are identical, Triple Rest focuses on out-of-the-box usage. To avoid disrupting existing services, it logs a warning by default. At runtime, if it cannot determine the highest priority mapping, an error will be thrown.
Supported parameter types vary by dialect. Please refer to the specific dialect’s guide for more details. You can also customize parameter resolution by implementing the SPI
org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver
.
Name | Description | Basic Annotation | SpringMVC Annotation | JAX-RS Annotation | Array or Collection Handling | Map Handling |
---|---|---|---|---|---|---|
Param | Query or Form parameter | @Param | @RequestParam | - | Multi-value | Map of all parameters |
Query | URL parameter | - | - | @QueryParam | Multi-value | Map of all Query parameters |
Form | Form parameter | - | - | @FormParam | Multi-value | Map of all Form parameters |
Header | HTTP header | @Param(type=Header) | @RequestHeader | @HeaderParam | Multi-value | Map of all Headers |
Cookie | Cookie value | @Param(type=Cookie) | @CookieValue | @CookieParam | Multi-value | Map of all Cookies |
Attribute | Request attribute | @Param(type=Attribute) | @RequestAttribute | - | Multi-value | Map of all Attributes |
Part | Multipart file | @Param(type=Part) | @RequestHeader | @HeaderParam | Multi-value | Map of all Parts |
Body | Request body | @Param(type=Body) | @RequestBody | @Body | Attempts to parse as array or collection | Attempts to parse as target type |
PathVariable | Path variable | @Param(type=PathVariable) | @PathVariable | @PathParam | Single-value array or collection | Single-value Map |
MatrixVariable | Matrix variable | @Param(type=MatrixVariable) | @MatrixVariable | @MatrixParam | Multi-value | Single-value Map |
Bean | Java Bean | No annotation needed | @ModelAttribute | @BeanParam | Attempts to parse as Bean array or collection | - |
Type | Description | Activation Condition |
---|---|---|
org.apache.dubbo.remoting.http12.HttpRequest | HttpRequest object | Activated by default |
org.apache.dubbo.remoting.http12.HttpResponse | HttpResponse object | Activated by default |
org.apache.dubbo.remoting.http12.HttpMethods | HTTP request method | Activated by default |
java.util.Locale | Request Locale | Activated by default |
java.io.InputStream | Request InputStream | Activated by default |
java.io.OutputStream | Response OutputStream | Activated by default |
javax.servlet.http.HttpServletRequest | Servlet HttpRequest object | Requires Servlet API jar |
javax.servlet.http.HttpServletResponse | Servlet HttpResponse object | Same as above |
javax.servlet.http.HttpSession | Servlet HttpSession object | Same as above |
javax.servlet.http.Cookie | Servlet Cookie object | Same as above |
java.io.Reader | Servlet Request Reader object | Same as above |
java.io.Writer | Servlet Response Writer object | Same as above |
The handling varies by dialect; refer to the specific dialect’s guide.
You can use RpcContext
to retrieve them:
// Dubbo http req/resp
HttpRequest request = RpcContext.getServiceContext().getRequest(HttpRequest.class);
HttpResponse response = RpcContext.getServiceContext().getRequest(HttpResponse.class);
// Servlet http req/resp
HttpServletRequest request = RpcContext.getServiceContext().getRequest(HttpServletRequest.class);
HttpServletResponse response = RpcContext.getServiceContext().getRequest(HttpServletResponse.class);
After obtaining the request, you can access some built-in attributes through attribute
.
See: RestConstants.java
By default, most parameter type conversions from String
to target types are supported, including:
Optional
, etc.)Generic types, including complex nesting, are fully supported. For implementation details, refer
to: GeneralTypeConverter.java.
Custom parameter type conversion can also be achieved by implementing SPI org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentConverter
.
Source Type | Target Type | Description | Default Value |
---|---|---|---|
String | double | Converts to a double | 0.0d |
String | float | Converts to a float | 0.0f |
String | long | Converts to a long | 0L |
String | int | Converts to an integer | 0 |
String | short | Converts to a short | 0 |
String | char | Converts to a character | 0 |
String | byte | Converts to a byte | 0 |
String | boolean | Converts to a boolean | false |
String | BigInteger | Converts to a BigInteger | null |
String | BigDecimal | Converts to a BigDecimal | null |
String | Date | Converts to a Date | null |
String | Calendar | Converts to a Calendar | null |
String | Timestamp | Converts to a Timestamp | null |
String | Instant | Converts to an Instant | null |
String | ZonedDateTime | Converts to a ZonedDateTime | null |
String | LocalDate | Converts to a LocalDate | null |
String | LocalTime | Converts to a LocalTime | null |
String | LocalDateTime | Converts to a LocalDateTime | null |
String | ZoneId | Converts to a ZoneId | null |
String | TimeZone | Converts to a TimeZone | null |
String | File | Converts to a File | null |
String | Path | Converts to a Path | null |
String | Charset | Converts to a Charset | null |
String | InetAddress | Converts to an InetAddress | null |
String | URI | Converts to a URI | null |
String | URL | Converts to a URL | null |
String | UUID | Converts to a UUID | null |
String | Locale | Converts to a Locale | null |
String | Currency | Converts to a Currency | null |
String | Pattern | Converts to a Pattern | null |
String | Class | Converts to a Class | null |
String | byte[] | Converts to a byte array | null |
String | char[] | Converts to a char array | null |
String | OptionalInt | Converts to an OptionalInt | null |
String | OptionalLong | Converts to an OptionalLong | null |
String | OptionalDouble | Converts to an OptionalDouble | null |
String | Enum class | Enum.valueOf | null |
String | Array or Collection | Split by comma | null |
String | Specified class | Try JSON String to Object | null |
String | Specified class | Try construct with single String | null |
String | Specified class | Try call static method valueOf | null |
By default, the following Content-Types are supported with corresponding encoding and decoding capabilities. Extension is available by implementing SPI
org.apache.dubbo.remoting.http12.message.(HttpMessageDecoderFactory|HttpMessageEncoderFactory)
.
Media Type | Description |
---|---|
application/json | JSON format |
application/xml | XML format |
application/yaml | YAML format |
application/octet-stream | Binary data |
application/grpc | gRPC format |
application/grpc+proto | gRPC with Protocol Buffers |
application/x-www-form-urlencoded | URL-encoded form data |
multipart/form-data | Form data with file upload |
text/json | JSON format as text |
text/xml | XML format as text |
text/yaml | YAML format as text |
text/css | CSS format |
text/javascript | JavaScript format as text |
text/html | HTML format |
text/plain | Plain text |
Supports comprehensive content negotiation to determine the output Content-Type based on mapping or input. The process is as follows:
@RequestMapping(produces = "application/json")
Accept
header, and match wildcard to appropriate Media Type. For example: Accept: application/json
/hello?format=yml
/hello.txt
Content-Type: application/json
application/json
Provides full CORS support, enabled by configuring global parameters. Default behavior is consistent with SpringMVC. Fine-grained configuration is also supported through
@CrossOrigin
in SpringMVC. For supported CORS configuration items, refer to: 8.4 CORS Configuration
Custom HTTP output is required in many scenarios, such as 302 redirects or setting HTTP headers. Triple Rest offers the following generic solutions, with dialect-specific approaches available in each dialect’s user guide:
org.apache.dubbo.remoting.http12.HttpResult
and build using HttpResult#builder
.throws new org.apache.dubbo.remoting.http12.exception.HttpResultPayloadException(HttpResult)
. Example code:throw new HttpResult.found("https://a.com").
toPayload();
This exception avoids filling error stacks, has minimal performance impact, and does not require return value logic, making it recommended for customizing output.
HttpResponse response = RpcContext.getServiceContext().getRequest(HttpResponse.class);
response.
sendRedirect("https://a.com");
response.
setStatus(404);
response.
outputStream().
write(data);
// It is recommended to commit after writing to avoid being modified by other extensions
response.
commit();
If only adding http headers
, use this method.
Multiple JSON frameworks are supported, including Jackson, fastjson2, fastjson, and gson. Please ensure that the corresponding jar dependencies have been imported before use.
dubbo.protocol.triple.rest.json-framework=jackson
You can customize JSON processing by implementing the SPI org.apache.dubbo.common.json.JsonUtil
. For specific examples, you can refer to the existing implementations
in org/apache/dubbo/common/json/impl. It is recommended to extend an
existing implementation and override as needed.
Unhandled exceptions are ultimately converted to the ErrorResponse
class and encoded for output:
@Data
public class ErrorResponse {
/**
* HTTP status code
*/
private String status;
/**
* Exception message
*/
private String message;
}
Note that for errors with status 500 and above, to avoid disclosing internal server information, the default message output is “Internal Server Error”. To customize the message,
create an exception that extends org.apache.dubbo.remoting.http12.exception.HttpStatusException
and override the getDisplayMessage
method.
The following general methods
are available for customizing exception handling:
org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilterAdapter
.org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter
to transform exceptions, which is more lightweight and provides path matching configuration capabilities.Note that the latter two methods only intercept exceptions occurring in the invoke chain. If exceptions occur during path matching, only method 1 can handle them.
See example: dubbo-samples-triple-rest/dubbo-samples-triple-rest-basic
Basic, as an out-of-the-box REST mapping, will by default map methods to: /{contextPath}/{serviceInterface}/{methodName}
, where /{contextPath}
will be ignored if not
configured, resulting in: /{serviceInterface}/{methodName}
.
Custom mappings are supported through the org.apache.dubbo.remoting.http12.rest.Mapping
annotation. The
attribute descriptions are as follows:
Config Name | Description | Default Behavior |
---|---|---|
value | Mapped URL paths, which can be one or more paths. | Empty array |
path | Mapped URL paths, same as value , can be one or more paths. | Empty array |
method | Supported HTTP methods list, such as GET , POST , etc. | Empty array (supports all methods) |
params | List of parameters that must be included in the request. | Empty array |
headers | List of headers that must be included in the request. | Empty array |
consumes | Content types (Content-Type) for processing requests, which can be one or more types. | Empty array |
produces | Content types (Content-Type) for generating responses, which can be one or more types. | Empty array |
enabled | Whether to enable this mapping. | true (enabled) |
@Mapping("${prefix}/hi")
@Mapping(enabled = false)
General parameters are discussed in: 3.2 Parameter Types
Basic supports parameters without annotations through the
class: FallbackArgumentResolver.java.
The detailed processing flow is as follows:
See example: dubbo-samples-triple-rest/dubbo-samples-triple-rest-springmvc
Refer directly to the SpringMVC documentation, which supports most
features, Mapping Requests :: Spring Framework
Note that @Controller
or @RestController
annotations are not required; in addition to @RequestMapping
, the new @HttpExchange
is also supported.
See: 3.2 Parameter Types
See 3.2.1 Annotated Parameter Types
Type | Description | Activation Condition |
---|---|---|
org.springframework.web.context.request.WebRequest | WebRequest object | SpringWeb dependency required |
org.springframework.web.context.request.NativeWebRequest | NativeWebRequest object | Same as above |
org.springframework.http.HttpEntity | Http entity | Same as above |
org.springframework.http.HttpHeaders | Http headers | Same as above |
org.springframework.util.MultiValueMap | Multi-value map | Same as above |
Prefer using Spring’s org.springframework.core.convert.ConversionService
to convert parameters. For Spring Boot applications, the default is mvcConversionService
; otherwise,
use org.springframework.core.convert.support.DefaultConversionService#getSharedInstance
to obtain the shared ConversionService
.
If ConversionService
does not support it,
it will fall back to general type conversion: 3.3 Parameter Type Conversion
In addition to supporting the methods mentioned in 3.8 Exception Handling, Spring’s @ExceptionHandler
annotation method is also
supported, Exceptions :: Spring Framework. Note that this method only
handles exceptions thrown during method calls; other exceptions cannot be captured.
In addition to supporting global CORS configuration as described in 8.4 CORS Configuration, Spring’s @CrossOrigin
allows for fine-grained
configuration, CORS :: Spring Framework.
Supports the following Spring customization methods:
See example: dubbo-samples-triple-rest/dubbo-samples-triple-rest-jaxrs
Services need to explicitly add the @Path annotation, and methods need to add request method annotations like @GET, @POST, @HEAD.
Refer directly to the Resteasy documentation,
which supports most features, Chapter 4. Using @Path and @GET, @POST, etc.
See: 3.2 Parameter Types
Annotation | Parameter Location | Description |
---|---|---|
@QueryParam | querystring | Parameters corresponding to ?a=a&b=b |
@HeaderParam | header | |
@PathParam | path | |
@FormParam | form | body in key1=value2&key2=value2 format |
No annotation | body | Not explicitly annotated |
Type | Description | Activation Condition |
---|---|---|
javax.ws.rs.core.Cookie | Cookie object | Requires Jax-rs dependency |
javax.ws.rs.core.Form | Form object | Same as above |
javax.ws.rs.core.HttpHeaders | Http headers | Same as above |
javax.ws.rs.core.MediaType | Media type | Same as above |
javax.ws.rs.core.MultivaluedMap | Multivalued Map | Same as above |
javax.ws.rs.core.UriInfo | Uri information | Same as above |
Custom parameter conversion can be extended via the following interfaces:
org.apache.dubbo.rpc.protocol.tri.rest.argument.ArgumentResolver
javax.ws.rs.ext.ParamConverterProvider
Custom exception handling can be extended via the following interfaces:
javax.ws.rs.ext.ExceptionMapper
org.apache.dubbo.remoting.http12.ExceptionHandler
Supports 8.4 CORS Configuration global configuration
Supports the following JAX-RS customizations:
For both lower version javax and higher version jakarta servlet APIs, jakarta API has higher priority. Simply include the jar to use HttpServletRequest and HttpServletResponse as parameters.
Method 1: Implement Filter
interface and org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension
interface, then register SPI
import org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension;
import javax.servlet.Filter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class DemoFilter implements Filter, RestExtension {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
chain.doFilter(request, response);
}
@Override
public String[] getPatterns() {
return new String[]{"/demo/**", "!/demo/one"};
}
@Override
public int getPriority() {
return -200;
}
}
Method 2: Implement Supplier<Filter>
interface and org.apache.dubbo.rpc.protocol.tri.rest.filter.RestExtension
interface, then register SPI
public class DemoFilter implements Supplier<Filter>, RestExtension {
private final Filter filter = new SsoFilter();
@Override
public Filter get() {
return filter;
}
}
This method is convenient for reusing existing Filters, and can even obtain Filter instances from Spring Context and register them
public class DemoFilter implements Supplier<Filter>, RestExtension {
private final Filter filter = new SsoFilter();
public DemoFilter(FrameworkModel frameworkModel) {
SpringExtensionInjector injector = SpringExtensionInjector.get(frameworkModel.defaultApplication());
filter = injector.getInstance(SsoFilter.class, null);
}
@Override
public Filter get() {
return filter;
}
}
Implement SPI org.apache.dubbo.rpc.protocol.tri.rest.support.servlet.HttpSessionFactory
request.getRequestDispatcher
is not supported
When Rest services open direct access to the public network, there are security risks of potential attacks. Therefore, before exposing services, it’s necessary to thoroughly assess the risks and choose appropriate authentication methods to ensure security. Triple provides various security authentication mechanisms, and users can also implement their own extensions to perform security checks on access.
To enable Basic Authentication, modify the following configuration:
dubbo:
provider:
auth: true
authenticator: basic
username: admin
password: admin
Once enabled, all HTTP requests will require Basic Authentication to access.
For RPC calls, you also need to configure the corresponding username and password on the consumer side:
dubbo:
consumer:
auth: true
authenticator: basic
username: admin
password: admin
With this configuration, communication between provider and consumer will use Basic Authentication to ensure security. Make sure to use strong passwords in production environments and consider using HTTPS for encrypted transmission.
You can customize authentication by implementing the SPI org.apache.dubbo.auth.spi.Authenticator
, and select the Authenticator to enable through the configuration
dubbo.provider.authenticator
.
You can customize HTTP filtering logic by implementing the SPI org.apache.dubbo.rpc.HeaderFilter
or org.apache.dubbo.rpc.protocol.tri.rest.filter.RestFilter
.
Configuration Name: dubbo.protocol.triple.rest.case-sensitive-match
Whether path matching should be case-sensitive. If enabled, methods mapped to /users
will not match
/Users
Default is true
Configuration Name: dubbo.protocol.triple.rest.trailing-slash-match
Whether path matching should match paths with trailing slashes. If enabled, methods mapped to /users
will also match /users/
Default is true
Configuration Name: dubbo.protocol.triple.rest.suffix-pattern-match
Whether path matching uses suffix pattern matching (.*). If enabled, methods mapped to /users
will also
match /users.*
, with suffix content negotiation enabled, media types inferred from URL suffix, e.g., .json
corresponds to application/json
Default is true
Configuration Name | Description | Default Value |
---|---|---|
dubbo.protocol.triple.rest.cors.allowed-origins | List of allowed origins for cross-origin requests, can be specific domains or * for all origins. | Not set (no origins allowed) |
dubbo.protocol.triple.rest.cors.allowed-methods | List of allowed HTTP methods, e.g., GET , POST , PUT , * for all methods. | Not set (only GET and HEAD ) |
dubbo.protocol.triple.rest.cors.allowed-headers | List of allowed request headers in preflight requests, * for all headers. | Not set |
dubbo.protocol.triple.rest.cors.exposed-headers | List of response headers exposed to clients, * for all headers. | Not set |
dubbo.protocol.triple.rest.cors.allow-credentials | Whether user credentials are supported. | Not set (user credentials not supported) |
dubbo.protocol.triple.rest.cors.max-age | Time (in seconds) that the client can cache the preflight request response. | Not set |
Custom exception handling logic can be implemented via the SPI org.apache.dubbo.remoting.http12.ExceptionHandler
public interface ExceptionHandler<E extends Throwable, T> {
/**
* Resolves the log level for a given throwable.
*/
default Level resolveLogLevel(E throwable) {
return null;
}
/**
* Handle the exception and return a result.
*/
default T handle(E throwable, RequestMetadata metadata, MethodDescriptor descriptor) {
return null;
}
}
Implement SPI and specify the exception type E to handle
org.apache.dubbo.remoting.http12.HttpResult
.
logging:
level:
"org.apache.dubbo.rpc.protocol.tri": debug
"org.apache.dubbo.remoting": debug
Enable debug logging will output detailed startup logs and request/response logs for troubleshooting.
dubbo:
protocol:
triple:
verbose: true
Enable verbose output will return internal error stack traces to the caller and output more error logs for troubleshooting.