Skip to content

Commit d915b66

Browse files
authored
Merge pull request iluwatar#755 from okinskas/ambassador
Ambassador Pattern iluwatar#722
2 parents c7f9266 + 7add7b8 commit d915b66

File tree

12 files changed

+653
-1
lines changed

12 files changed

+653
-1
lines changed

ambassador/README.md

+178
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
layout: pattern
3+
title: Ambassador
4+
folder: ambassador
5+
permalink: /patterns/ambassador/
6+
categories: Structural
7+
tags:
8+
- Java
9+
- Difficulty-Intermediate
10+
---
11+
12+
## Intent
13+
Provide a helper service instance on a client and offload common functionality away from a shared resource.
14+
15+
## Explanation
16+
Real world example
17+
18+
> A remote service has many clients accessing a function it provides. The service is a legacy application and is impossible to update. Large numbers of requests from users are causing connectivity issues. New rules for request frequency should be implemented along with latency checks and client-side logging.
19+
20+
In plain words
21+
22+
> Using the ambassador pattern, we can implement less-frequent polling from clients along with latency checks and logging.
23+
24+
Microsoft documentation states
25+
26+
> An ambassador service can be thought of as an out-of-process proxy that is co-located with the client.
27+
This pattern can be useful for offloading common client connectivity tasks such as monitoring, logging, routing, security (such as TLS), and resiliency patterns in a language agnostic way. It is often used with legacy applications, or other applications that are difficult to modify, in order to extend their networking capabilities. It can also enable a specialized team to implement those features.
28+
29+
**Programmatic Example**
30+
31+
With the above example in mind we will imitate the functionality in a simple manner. We have an interface implemented by the remote service as well as the ambassador service:
32+
33+
```java
34+
interface RemoteServiceInterface {
35+
36+
long doRemoteFunction(int value) throws Exception;
37+
}
38+
```
39+
40+
A remote services represented as a singleton.
41+
42+
```java
43+
public class RemoteService implements RemoteServiceInterface {
44+
45+
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
46+
private static RemoteService service = null;2
47+
48+
static synchronized RemoteService getRemoteService() {
49+
if (service == null) {
50+
service = new RemoteService();
51+
}
52+
return service;
53+
}
54+
55+
private RemoteService() {}
56+
57+
@Override
58+
public long doRemoteFunction(int value) {
59+
60+
long waitTime = (long) Math.floor(Math.random() * 1000);
61+
62+
try {
63+
sleep(waitTime);
64+
} catch (InterruptedException e) {
65+
LOGGER.error("Thread sleep interrupted", e)
66+
}
67+
return waitTime >= 200 ? value * 10 : -1;
68+
}
69+
}
70+
```
71+
72+
A service ambassador adding additional features such as logging, latency checks
73+
74+
```java
75+
public class ServiceAmbassador implements RemoteServiceInterface {
76+
77+
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
78+
private static final int RETRIES = 3;
79+
private static final int DELAY_MS = 3000;
80+
81+
ServiceAmbassador() {}
82+
83+
@Override
84+
public long doRemoteFunction(int value) {
85+
86+
return safeCall(value);
87+
}
88+
89+
private long checkLatency(int value) {
90+
RemoteService service = RemoteService.getRemoteService();
91+
long startTime = System.currentTimeMillis();
92+
long result = service.doRemoteFunction(value);
93+
long timeTaken = System.currentTimeMillis() - startTime;
94+
95+
LOGGER.info("Time taken (ms): " + timeTaken);
96+
return result;
97+
}
98+
99+
private long safeCall(int value) {
100+
101+
int retries = 0;
102+
long result = -1;
103+
104+
for (int i = 0; i < RETRIES; i++) {
105+
106+
if (retries >= RETRIES) {
107+
return -1;
108+
}
109+
110+
if ((result = checkLatency(value)) == -1) {
111+
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
112+
retries++;
113+
try {
114+
sleep(DELAY_MS);
115+
} catch (InterruptedException e) {
116+
LOGGER.error("Thread sleep state interrupted", e);
117+
}
118+
} else {
119+
break;
120+
}
121+
}
122+
return result;
123+
}
124+
}
125+
```
126+
127+
A client has a local service ambassador used to interact with the remote service:
128+
129+
```java
130+
public class Client {
131+
132+
private ServiceAmbassador serviceAmbassador;
133+
134+
Client() {
135+
serviceAmbassador = new ServiceAmbassador();
136+
}
137+
138+
long useService(int value) {
139+
long result = serviceAmbassador.doRemoteFunction(value);
140+
LOGGER.info("Service result: " + result)
141+
return result;
142+
}
143+
}
144+
```
145+
146+
And here are two clients using the service.
147+
148+
```java
149+
Client host1 = new Client();
150+
Client host2 = new Client();
151+
host1.useService(12);
152+
host2.useService(73);
153+
```
154+
155+
## Applicability
156+
Ambassador is applicable when working with a legacy remote service that cannot
157+
be modified or would be extremely difficult to modify. Connectivity features can
158+
be implemented on the client avoiding the need for changes on the remote service.
159+
160+
* Ambassador provides a local interface for a remote service.
161+
* Ambassador provides logging, circuit breaking, retries and security on the client.
162+
163+
## Typical Use Case
164+
165+
* Control access to another object
166+
* Implement logging
167+
* Implement circuit breaking
168+
* Offload remote service tasks
169+
* Facilitate network connection
170+
171+
## Real world examples
172+
173+
* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador)
174+
175+
## Credits
176+
177+
* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador)
178+
* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://books.google.co.uk/books?id=6BJNDwAAQBAJ&pg=PT35&lpg=PT35&dq=ambassador+pattern+in+real+world&source=bl&ots=d2e7GhYdHi&sig=Lfl_MDnCgn6lUcjzOg4GXrN13bQ&hl=en&sa=X&ved=0ahUKEwjk9L_18rrbAhVpKcAKHX_KA7EQ6AEIWTAI#v=onepage&q=ambassador%20pattern%20in%20real%20world&f=false)

ambassador/pom.xml

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
4+
The MIT License
5+
Copyright (c) 2014-2016 Ilkka Seppälä
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the "Software"), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in
15+
all copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
THE SOFTWARE.
24+
25+
-->
26+
<project xmlns="http://maven.apache.org/POM/4.0.0"
27+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
28+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
29+
<parent>
30+
<artifactId>java-design-patterns</artifactId>
31+
<groupId>com.iluwatar</groupId>
32+
<version>1.20.0-SNAPSHOT</version>
33+
</parent>
34+
<modelVersion>4.0.0</modelVersion>
35+
<artifactId>ambassador</artifactId>
36+
<dependencies>
37+
<dependency>
38+
<groupId>org.junit.jupiter</groupId>
39+
<artifactId>junit-jupiter-api</artifactId>
40+
<scope>test</scope>
41+
</dependency>
42+
<dependency>
43+
<groupId>org.junit.jupiter</groupId>
44+
<artifactId>junit-jupiter-engine</artifactId>
45+
<scope>test</scope>
46+
</dependency>
47+
</dependencies>
48+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.ambassador;
24+
25+
/**
26+
*
27+
* The ambassador pattern creates a helper service that sends network requests on behalf of a
28+
* client. It is often used in cloud-based applications to offload features of a remote service.
29+
*
30+
* An ambassador service can be thought of as an out-of-process proxy that is co-located with
31+
* the client. Similar to the proxy design pattern, the ambassador service provides an interface
32+
* for another remote service. In addition to the interface, the ambassador provides extra
33+
* functionality and features, specifically offloaded common connectivity tasks. This usually
34+
* consists of monitoring, logging, routing, security etc. This is extremely useful in
35+
* legacy applications where the codebase is difficult to modify and allows for improvements
36+
* in the application's networking capabilities.
37+
*
38+
* In this example, we will the ({@link ServiceAmbassador}) class represents the ambassador while the
39+
* ({@link RemoteService}) class represents a remote application.
40+
*
41+
*/
42+
public class App {
43+
44+
/**
45+
* Entry point
46+
*/
47+
public static void main(String[] args) {
48+
Client host1 = new Client();
49+
Client host2 = new Client();
50+
host1.useService(12);
51+
host2.useService(73);
52+
}
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.ambassador;
24+
25+
import org.slf4j.LoggerFactory;
26+
27+
import org.slf4j.Logger;
28+
29+
/**
30+
* A simple Client
31+
*/
32+
public class Client {
33+
34+
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
35+
private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
36+
37+
long useService(int value) {
38+
long result = serviceAmbassador.doRemoteFunction(value);
39+
LOGGER.info("Service result: " + result);
40+
return result;
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014-2016 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.ambassador;
24+
25+
import org.slf4j.Logger;
26+
import org.slf4j.LoggerFactory;
27+
28+
import static java.lang.Thread.sleep;
29+
30+
/**
31+
* A remote legacy application represented by a Singleton implementation.
32+
*/
33+
public class RemoteService implements RemoteServiceInterface {
34+
35+
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
36+
private static RemoteService service = null;
37+
38+
static synchronized RemoteService getRemoteService() {
39+
if (service == null) {
40+
service = new RemoteService();
41+
}
42+
return service;
43+
}
44+
45+
private RemoteService() {}
46+
47+
/**
48+
* Remote function takes a value and multiplies it by 10 taking a random amount of time.
49+
* Will sometimes return -1. This imitates connectivity issues a client might have to account for.
50+
* @param value integer value to be multiplied.
51+
* @return if waitTime is more than 200ms, it returns value * 10, otherwise -1.
52+
*/
53+
@Override
54+
public long doRemoteFunction(int value) {
55+
56+
long waitTime = (long) Math.floor(Math.random() * 1000);
57+
58+
try {
59+
sleep(waitTime);
60+
} catch (InterruptedException e) {
61+
LOGGER.error("Thread sleep state interrupted", e);
62+
}
63+
return waitTime >= 200 ? value * 10 : -1;
64+
}
65+
}

0 commit comments

Comments
 (0)