I have following Service:
public class ServerApp : AppHostHttpListenerPoolBase
{
public ServerApp() : base("Server", 500,
typeof(TestService).Assembly)
{
}
public override void Configure(Container container)
{
ThreadsPerProcessor = 50;
}
}
public class TestService : Service
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public object Any(Hello hello)
{
_logger.Info("Received: " + hello.Name);
var waitingMinutes = new Random().Next(1, 10);
Thread.Sleep(TimeSpan.FromMinutes(waitingMinutes));
_logger.Info("Response: " + hello.Name);
return new GoodBye(){Message = "Bye Bye " + hello.Name};
}
}
}
and I have simple test project to push Parallel request to the Service (and push all is ok), but Service only process 2 requests at a time. When a request has been processed, the next request should be processed.
How can I increase the concurrent process?
ServiceStack's AppHostHttpListenerPoolBase does execute Service concurrently by executing Services on new ThreadPool Threads.
To demonstrate this I've created a stand-alone example which executes 50 concurrent requests sleeping between 30-60s that calls the stand-alone test based on your Example in ConcurrencyTest.cs calling this Service:
public class SleepTest : IReturn<SleepTestResponse>
{
public string Name { get; set; }
public int WaitingSecs { get; set; }
}
public class SleepTestResponse
{
public string Message { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class TestConcurrencyService : Service
{
public object Any(SleepTest request)
{
var sw = Stopwatch.StartNew();
Thread.Sleep(TimeSpan.FromSeconds(request.WaitingSecs));
return new SleepTestResponse
{
Message = $"{request.Name} took {sw.Elapsed.TotalSeconds} secs",
};
}
}
Which is called with this client load test executing 50 concurrent requests waiting between 30-60s:
var rand = new Random();
var client = new JsonHttpClient(Config.AbsoluteBaseUri);
client.GetHttpClient().Timeout = TimeSpan.FromMinutes(5);
long responsesReceived = 0;
long totalSecondsWaited = 0;
var sw = Stopwatch.StartNew();
const int ConcurrentRequests = 50;
ConcurrentRequests.Times(i =>
{
Interlocked.Increment(ref responsesReceived);
ThreadPool.QueueUserWorkItem(async _ => {
var request = new SleepTest {
Name = $"Request {i+1}",
WaitingSecs = rand.Next(30, 60),
};
Interlocked.Add(ref totalSecondsWaited, request.WaitingSecs);
log.Info($"[{DateTime.Now.TimeOfDay}] Sending {request.Name} to sleep for {request.WaitingSecs} seconds...");
try
{
var response = await client.GetAsync(request);
log.Info($"[{DateTime.Now.TimeOfDay}] Received {request.Name}: {response.Message}");
}
catch (Exception ex)
{
log.Error($"[{DateTime.Now.TimeOfDay}] Error Response: {ex.UnwrapIfSingleException().Message}", ex);
}
finally
{
Interlocked.Decrement(ref responsesReceived);
}
});
});
Which waits for all threads to finish with:
while (Interlocked.Read(ref responsesReceived) > 0)
{
Thread.Sleep(10);
}
log.Info($"Took {sw.Elapsed.TotalSeconds} to execute {ConcurrentRequests} Concurrent Requests waiting a total of {totalSecondsWaited} seconds.");
Which results in:
INFO: Took 246.4556327 to execute 50 Concurrent Requests waiting a total of 2228 seconds.
i.e a lot less than it would've taken if the requests weren't executed concurrently.
The full log for all requests showing the requests were executed just marginally longer than the server was requested to wait for.
The 2 concurrency limit you're indicating suggests it's a http client connection limit per domain. You should make sure you're using a load testing tool that doesn't have these limits like wrk or apacahe bench.
Use .NET Core for best performance
Note if you want maximum throughput for Self Hosting ServiceStack Services we recommend running ServiceStack on .NET Core, preferably on the .NET Core runtime, but if you need to, you can also run ServiceStack ASP.NET Core on the .NET Framework.
Related
I could create a server lease to a single client as follows:
#Slf4j
public class LeaseServer {
private static final String SERVER_TAG = "server";
public static void main(String[] args) throws InterruptedException {
// Queue for incoming messages represented as Flux
// Imagine that every fireAndForget that is pushed is processed by a worker
int queueCapacity = 50;
BlockingQueue<String> messagesQueue = new ArrayBlockingQueue<>(queueCapacity);
// emulating a worker that process data from the queue
Thread workerThread =
new Thread(
() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
String message = messagesQueue.take();
System.out.println("consume message:" + message);
Thread.sleep(100000); // emulating processing
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
workerThread.start();
CloseableChannel server = getFireAndForgetServer(messagesQueue, workerThread);
TimeUnit.MINUTES.sleep(10);
server.dispose();
}
private static CloseableChannel getFireAndForgetServer(BlockingQueue<String> messagesQueue, Thread workerThread) {
CloseableChannel server =
RSocketServer.create((setup, sendingSocket) ->
Mono.just(new RSocket() {
#Override
public Mono<Void> fireAndForget(Payload payload) {
// add element. if overflows errors and terminates execution
// specifically to show that lease can limit rate of fnf requests in
// that example
try {
if (!messagesQueue.offer(payload.getDataUtf8())) {
System.out.println("Queue has been overflowed. Terminating execution");
sendingSocket.dispose();
workerThread.interrupt();
}
} finally {
payload.release();
}
return Mono.empty();
}
}))
.lease(() -> Leases.create().sender(new LeaseCalculator(SERVER_TAG, messagesQueue)))
.bindNow(TcpServerTransport.create("localhost", 7000));
return server;
}
}
But how do I issue a lease to multiple clients connected to that server?
Otherwise my queue will be written multiple times by multiple clients, resulting in an overflow of the service.
I can't find the details in the public documents and materials.
Your help was very much appreciated.
I need another pair of eyes to take a look at this. It's driving me nuts.
I am intermittently getting a 'System.AggregateException' when running a console app that connects to a web api.
I am doing this in a local testing environment through visual studio(IIS Express).
As stated, I have two different apps running locally on IIS Express(2 different ports). One is a console app and the other is a web api. The console app connects to the web api.
It's about 50/50 if it works or not. 50% of the time it works fine and spits out the expected results. But the other 50% of the time, it fails with the errors below. When it does fail, it's always immediate, like 2 or 3 seconds after starting the console app.
After some Googling and fiddling around with various settings, I know it's not either of these:
not a timeout issue
not a firewall issue
I've tried setting breakpoints at various points, but it never really reveals anything significant.
The exception I get when it fails is:
An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code
Here is the inner exception:
No connection could be made because the target machine actively refused it http://localhost:45321
The stack trace indicates:
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task1.get_Result()
at BeatGenerator.BeatGeneratorMain.<>c.b__2_0(Task1 postTask) in C:\Users\xxx\Documents\VS2012\DrumBeats\BeatGenerator\BeatGeneratorMain.cs:line 72
at System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Here is the error line:
var response = await http.PostAsJsonAsync("http://localhost:45321/api/drumcorp/beats/generate", drumbeat)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
This is the console app that connects to API controller:
public class DrumBeats
{
public int StartBeat { get; set; }
public int EndBeat { get; set; }
public int ChordId { get; set; }
}
public class BeatGeneratorMain
{
static void Main(string[] args)
{
Generate().Wait();
}
private static async Task Generate()
{
var drumbeat = new DrumBeats();
drumbeat.ChordId = 122;
drumbeat.StartBeat = 2;
drumbeat.EndBeat = 4;
var creds = new NetworkCredential("testUser", "xxxx", "xxx"); //username, pw, domain
var handler = new HttpClientHandler { Credentials = creds };
using (var http = new HttpClient(handler))
{
http.Timeout = TimeSpan.FromMinutes(10);
var response = await http.PostAsJsonAsync("http://localhost:45321/api/drumcorp/beats/generate", drumbeat)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}
}
This is the relevant section of the web api controller app:
public class DrumBeats //same as in console app
{
public int StartBeat { get; set; }
public int EndBeat { get; set; }
public int ChordId { get; set; }
}
[HttpPost("api/drumcorp/beats/generate")]
public string PostMethodBeats([FromBody] DrumBeats drumbeat)
{
string beatsChart = DrumBeatMaster.ReturnBeatsChart(DrumBeats.ChordId, DrumBeats.StartBeat, DrumBeats.EndBeat);
var mesg = "<b>Beats Created</b><br /><br /> ";
return mesg + beatsChart;
}
DrumBeatMaster.ReturnBeatsChart is just a simple helper method that processes the beats and spits out a string.
To understand what is the exception you will have to catch the aggregate exception and throw them flattened like
try
{
// Your code
}
catch (AggregateException agg)
{
throw agg.Flatten();
}
I've tried to come up with something from the example in the WebJobsSDK gitHub
var eventHubConfig = new EventHubConfiguration();
string eventHubName = "MyHubName";
eventHubConfig.AddSender(eventHubName,"Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=SendRule;SharedAccessKey=xxxxxxxx");
eventHubConfig.AddReceiver(eventHubName, "Endpoint=sb://test.servicebus.windows.net/;SharedAccessKeyName=ReceiveRule;SharedAccessKey=yyyyyyy");
config.UseEventHub(eventHubConfig);
JobHost host = new JobHost(config);
But I'm afraid that's not far enough for someone of my limited "skillset"!
I can find no instance of JobHostConfiguration that has a UseEventHub property (using the v1.2.0-alpha-10291 version of the Microsoft.AzureWebJobs package), so I can't pass the EventHubConfiguration to the JobHost.
I've used EventHub before, not within the WebJob context. I don't see if the EventHostProcessor is still required if using the WebJob triggering...or does the WebJob trigger essentially act as the EventHostProcessor?
Anyway, if anyone has a more complete example for a simpleton like me that would be really sweet! Thanks
From the documentation here, you should have all the information you need.
What you are missing is a reference of the Microsoft.Azure.WebJobs.ServiceBus.1.2.0-alpha-10291 nuget package.
The UseEventHub is an extension method that is declared in this package.
Otherwise your configuration seems ok.
Here is an example on how to receive or send messages from/to an EventHub:
public class BasicTest
{
public class Payload
{
public int Counter { get; set; }
}
public static void SendEvents([EventHub("MyHubName")] out Payload x)
{
x = new Payload { Counter = 100 };
}
public static void Trigger(
[EventHubTrigger("MyHubName")] Payload x,
[EventHub("MyHubName")] out Payload y)
{
x.Counter++;
y = x;
}
}
EventProcessorHost is still required, as the WebJob just provides the hosting environment for running it. As far as I know, EventProcessorHost is not integrated so deeply into WebJob, so its triggering mechanism cannot be used for processing EventHub messages. I use WebJob for running EventProcessorHost continuously:
public static void Main()
{
RunAsync().Wait();
}
private static async Task RunAsync()
{
try
{
using (var shutdownWatcher = new WebJobsShutdownWatcher())
{
await Console.Out.WriteLineAsync("Initializing...");
var eventProcessorHostName = "eventProcessorHostName";
var eventHubName = ConfigurationManager.AppSettings["eventHubName"];
var consumerGroupName = ConfigurationManager.AppSettings["eventHubConsumerGroupName"];
var eventHubConnectionString = ConfigurationManager.ConnectionStrings["EventHub"].ConnectionString;
var storageConnectionString = ConfigurationManager.ConnectionStrings["EventHubStorage"].ConnectionString;
var eventProcessorHost = new EventProcessorHost(eventProcessorHostName, eventHubName, consumerGroupName, eventHubConnectionString, storageConnectionString);
await Console.Out.WriteLineAsync("Registering event processors...");
var processorOptions = new EventProcessorOptions();
processorOptions.ExceptionReceived += ProcessorOptions_ExceptionReceived;
await eventProcessorHost.RegisterEventProcessorAsync<CustomEventProcessor>(processorOptions);
await Console.Out.WriteLineAsync("Processing...");
await Task.Delay(Timeout.Infinite, shutdownWatcher.Token);
await Console.Out.WriteLineAsync("Unregistering event processors...");
await eventProcessorHost.UnregisterEventProcessorAsync();
await Console.Out.WriteLineAsync("Finished.");
}
catch (Exception ex)
{
await HandleErrorAsync(ex);
}
}
}
private static async void ProcessorOptions_ExceptionReceived(object sender, ExceptionReceivedEventArgs e)
{
await HandleErrorAsync(e.Exception);
}
private static async Task HandleErrorAsync(Exception ex)
{
await Console.Error.WriteLineAsync($"Critical error occured: {ex.Message}{ex.StackTrace}");
}
I'm trying to write a target for NLog to send messages out to connected clients using SignalR.
Here's what I have now. What I'm wondering is should I be using resolving the ConnectionManager like this -or- somehow obtain a reference to the hub (SignalrTargetHub) and call a SendMessage method on it?
Are there performance ramifications for either?
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
public SignalR.IConnectionManager ConnectionManager { get; set; }
public SignalrTarget()
{
ConnectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
}
protected override void Write(NLog.LogEventInfo logEvent)
{
dynamic clients = GetClients();
var logEventObject = new
{
Message = this.Layout.Render(logEvent),
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff")
};
clients.onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return ConnectionManager.GetClients<SignalrTargetHub>();
}
}
I ended up with the basic the same basic structure that I started with. Just a few tweaks to get the information I needed.
Added exception details.
Html encoded the final message.
[Target("Signalr")]
public class SignalrTarget:TargetWithLayout
{
protected override void Write(NLog.LogEventInfo logEvent)
{
var sb = new System.Text.StringBuilder();
sb.Append(this.Layout.Render(logEvent));
if (logEvent.Exception != null)
sb.AppendLine().Append(logEvent.Exception.ToString());
var message = HttpUtility.HtmlEncode(sb.ToString());
var logEventObject = new
{
Message = message,
Logger = logEvent.LoggerName,
Level = logEvent.Level.Name,
TimeStamp = logEvent.TimeStamp.ToString("HH:mm:ss.fff")
};
GetClients().onLoggedEvent(logEventObject);
}
private dynamic GetClients()
{
return AspNetHost.DependencyResolver.Resolve<IConnectionManager>().GetClients<SignalrTargetHub>();
}
}
In my simple testing it's working well. Still remains to be seen if this adds any significant load when under stress.
After we have done some performance testing for our application which uses jackrabbit we faced with the huge problem with concurrent modification jackrabbit's repository. Problem appears when we add nodes or edit them in multithread emulation. Then I wrote very simple test which shows us that problem is not in our environment.
There is it:
Simple Stateless Bean
#Stateless
#Local(TestFacadeLocal.class)
#Remote(TestFacadeRemote.class)
public class TestFacadeBean implements TestFacadeRemote, TestFacadeLocal {
public void doAction(int name) throws Exception {
new TestSynch().doAction(name);
}
}
Simple class
public class TestSynch {
public void doAction(int name) throws Exception {
Session session = ((Repository) new InitialContext().
lookup("java:jcr/local")).login(
new SimpleCredentials("username", "pwd".toCharArray()));
List added = new ArrayList();
Node folder = session.getRootNode().getNode("test");
for (int i = 0; i <= 100; i++) {
Node child = folder.addNode("" + System.currentTimeMillis(),
"nt:folder");
child.addMixin("mix:versionable");
added.add(child);
}
// saving butch changes
session.save();
//checking in all created nodes
for (Node node : added) {
session.getWorkspace().getVersionManager().checkin(node.getPath());
}
}
}
And Test class
public class Test {
private int c = 0;
private int countAll = 50;
private ExecutorService executor = Executors.newFixedThreadPool(5);
public ExecutorService getExecutor() {
return executor;
}
public static void main(String[] args) {
Test test = new Test();
try {
test.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void start() throws Exception {
long time = System.currentTimeMillis();
TestFacadeRemote testBean = (TestFacadeRemote) getContext().
lookup( "test/TestFacadeBean/remote");
for (int i = 0; i < countAll; i++) {
getExecutor().execute(new TestInstallerThread(i, testBean));
}
getExecutor().shutdown();
while (!getExecutor().isTerminated()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(c + " shutdown " +
(System.currentTimeMillis() - time));
}
class TestInstallerThread implements Runnable {
private int number = 0;
TestFacadeRemote testBean;
public TestInstallerThread(int number, TestFacadeRemote testBean) {
this.number = number;
this.testBean = testBean;
}
#Override
public void run() {
try {
System.out.println("Installing data " + number);
testBean.doAction(number);
System.out.println("STOP" + number);
} catch (Exception e) {
e.printStackTrace();
c++;
}
}
}
public Context getContext() throws NamingException {
Properties properties = new Properties();
//init props
..............
return new InitialContext(properties);
}
}
If I initialized executor with 1 thread in pool all done without any error. If I initialized executor with 5 thread I got sometimes errors:
on client
java.lang.RuntimeException: javax.transaction.RollbackException: [com.arjuna.ats.internal.jta.transaction.arjunacore.commitwhenaborted] [com.arjuna.ats.internal.jta.transaction.arjunacore.commitwhenaborted] Can't commit because the transaction is in aborted state
at org.jboss.aspects.tx.TxPolicy.handleEndTransactionException(TxPolicy.java:198)
on server at the beginning warn
ItemStateReferenceCache [ItemStateReferenceCache.java:176] overwriting cached entry 187554a7-4c41-404b-b6ee-3ce2a9796a70
and then
javax.jcr.RepositoryException: org.apache.jackrabbit.core.state.ItemStateException: there's already a property state instance with id 52fb4b2c-3ef4-4fc5-9b79-f20a6b2e9ea3/{http://www.jcp.org/jcr/1.0}created
at org.apache.jackrabbit.core.PropertyImpl.restoreTransient(PropertyImpl.java:195) ~[jackrabbit-core-2.2.7.jar:2.2.7]
at org.apache.jackrabbit.core.ItemSaveOperation.restoreTransientItems(ItemSaveOperation.java:879) [jackrabbit-core-2.2.7.jar:2.2.7]
We have tried synchronize this method and other workflow for handle multithread calls as one thread. Nothing helps.
And one more thing - when we have done similar test without ejb layer - all worked fine.
It looks like container wrapped in own transaction and then all crashed.
Maybe somebody faced with such a problem.
Thanks in advance.
From the Jackrabbit Wiki:
The JCR specification explicitly states that a Session is not thread-safe (JCR 1.0 section 7.5 and JCR 2.0 section 4.1.2). Hence, Jackrabbit does not support multiple threads concurrently reading from or writing to the same session. Each session should only ever be accessed from one thread.
...
If you need to write to the same node concurrently, then you need to use multiple sessions, and use JCR locking to ensure there is no conflict.