I am trying to implement a shopping cart checkout() service that needs to make a call into two other rest services , one is to call products REST service to check final prices and then another is to make payment via Payments REST service. Should I be making these REST calls in my spring controller or spring service class?
It is best to separate the different concerns within the service itself. The controller in its nature, is responsible for mapping http requests and should not contain business logic as such.
It would be best to move the REST calls to the service layer of the checkout service.
However there is still room for improvement. Instead of the service layer making the REST calls, a sort of communicator module can be used to make the REST calls or handle the communication to the other services. Because today we might be using REST, tomorrow we can move to use gRPC etc. So it would be best to move the communications to another module.
Some code to bootstrap the structure;
Checkout controller
class CheckoutController {
#Autowired
private CheckoutService checkoutService;
#PostMapping("/checkout")
public string performCheckout(CheckoutDto checkoutDto){
checkoutService.performCheckout(checkoutDto);
}
}
Checkout service
class CheckoutService {
#Autowired
private PriceCheckerCommunicator priceCheckerCommunicator;
void performCheckout(CheckoutDto checkoutDto){
priceCheckerCommunicator.checkPrices(checkoutDto.getProductIds());
// the same will be done with the payment service as well
}
}
Price checker communicator
interface PriceCheckerCommunicator {
// the implementation of the interface will be calling the price checker service using REST call
void checkPrices(List<Long> productIds);
}
Here is an overview of the overall architecture;
Related
is it Ok if we call wep api service inside web form using api dll. we will be hosting both api and application on same server and requiring internal calling.
It's not very clear what you are after.
First of all if you write an API of some kind then you have to call it to interact with it. There's no middle ground here. If you don't want to call anything then you don't need an API. The purpose of an API is to provide a way to interact with some data storage, so behind your controllers you'd have a layer which talks to a database for example, or even another API.
If you don't want to make any calls then why bother with an API at all? Write a class library, one or several, doing whatever you need them to do and interact with your database this way.
I worked in a project before where I had a somewhat similar situation and ended up writing class libraries which were then shared by a UI project and a WebApi project, so you could work with them either way. This worked quite well actually. If you are looking for something similar then that's what I would go with. Keep the stuff of interest separate so you can expose with an API call or a direct dll reference.
So assuming that your controller methods look something like this:
public interface IService
{
Task<Value> GetValueAsync(int id);
}
public class Service : IService
{
public Task<Value> GetValueAsync(int id)
{
//...
// Code to return a value
//...
}
}
public class ValueController : ApiController
{
private IService _service;
public ValueController(IService service)
{
_service = service
}
public Task<IHttpActionResult> GetValueAsync(int id)
{
return Ok(await _service.GetValueAsync(id));
}
}
Then it is perfectly okay to call the method in the Service class. I would not call the method in the controller as that will cause more problems than you probably want to deal with.
I have Spring Web Application, which invokes content provider for some data. Its becoming common issue that content provider service is failing and app is becoming unresponsive. What would be best approach or design to check that content provider service is up or down at application level and handle it appropriately.
You can use circuit breaker pattern and Hystrix library.
It will monitor the method annotated with #HystrixCommand and if the failures amount to a certain threshold, it will start redirecting the calls to a fallbackMethod, allowing the continuation of service, and leaving you time to recover from failure.
A simple snippet that shows it in action is as follows:
#Service
public class BookService {
...
#HystrixCommand(fallbackMethod = "reliable")
public String readingList() {
...
}
public String reliable() {
...
}
}
I am hosting WebApi controller inside a stateless service with one instance. The service instance (I mean the instance of the WebApiService class created by the SF runtime) maintains some transient state as member fields, exposing the state through internal (thread-safe) methods. The WebApi controller needs to call the methods to access that state.
WebApiService.cs:
-----------------
internal sealed class WebApiService : StatelessService
{
private int _state;
internal int GetState() { return this._state; }
ServiceController.cs:
---------------------
public class ServiceController : ApiController
{
public async Task<IHttpActionResult> GetStateAsync()
{
// Here I'd like to grab somehow the WebApiService instance
// and call its GetState internal method.
My questions are:
How can the controller get a reference to the WebApiService instance?
Is it safe to store the WebApiService instance in a static field (perhaps set in the WebAspiService constructor)?
Inject the service instance as a dependency to your controllers through a DI container.
Here's an example with Web API hosted on Katana using Unity. It's a stateful service but it works exactly the same way for a stateless service: https://github.com/Azure-Samples/service-fabric-dotnet-getting-started/tree/master/Services/WordCount/WordCount.Service
Here's an example using Asp.Net Core and its built-in dependency injection container (also stateful, but same thing applies): https://github.com/vturecek/service-fabric-xray/tree/master/src/xray.Data
I think you could use a DI container for that. I can recommend simpleinjector (but there are many that can do the same), simpleinjector has got object lifetime management also per request and a web api package. You could put your state instance in a container as a singleton and inject it in your controllers, that would be a thread safe way, better stay away from static fields in a multithreaded web environment.
You have to resolve the stateless service in your controller before you can call the methods of the stateless service:
public async Task<IHttpActionResult> GetStateAsync()
{
var proxyLocation = new ServiceUriBuilder("WebApiService");
var svc = ServiceProxy.Create<IWebApiService>(proxyLocation.ToUri());
return svc.GetState();
}
You need to create an interface IWebApiService that contains the GetState method. WebApiService needs to implement it. Basically you need to abstract WebApiService with the IWebApiService interface.
I have the following code
public class MyService : IMyService
{
private readonoly IUnitOfWork _unitOfWork;
public MyService(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
}
//This code is used by web client
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IMyService>().To<MyService>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
}
I have a web and windows service client both use the "MyService" class. I want to dispose the "unit of work" at the end of HTTP request if the client is web, where as if the client is a windows service, I want to dispose the unit of work after every database call. how to achieve that? can I add an extra flag to the MyService constructor, to identify the client, but then how to modify the above code to pass a hardcoded value to that parameter when mapping the concrete types to the interfaces?
You will probably have some sort of MyServiceRunner in yourr Windows service that calls your MyService. This class is Windows service specific and this would be the place to explicitly control the lifetime of the IUnitOfWork. Or you can write a decorator for MyService that controls the unit of work.
A few things to note. Although you can reuse the IUnitOfWork on a per-web-request basis, DO NOT Commit the unit of work at the end of the web request, but explicitly do this after a service (succesfully) executed. Since the scope of your IUnitOfWork is very different in the Windows Service, you probably need some explicit code or explicit registration to handle this. However, make sure that your MyService is oblivious to this: It shouldn't need to care.
If you have many services that you want to call in the Windows Service, you might want to think about applying the command/handler pattern for handling business logic. You can read more about it here.
What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5
I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller.
I would like to develop the validation framework which can be utilized during web-services calls.
In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow.
Hope you get my point.
The Spring Validation framework can be used outside of Spring MVC. What WebServices Stack are you using? If you are using Spring-WS (Spring's Web Services stack) they have special instructions on how to set up the validator here:
http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html#d0e2313
If you are using some other stack, it is probably easier to implement something for that stack (or find one) that will use Spring's validation framework.
Recall that the Validator interface defines two methods:
boolean supports(Class clazz)
void validate(Object target, Errors errors)
The Object target is your form object, which is the whole object representing the page to be shown to the user. The Errors instance will contain the errors that will be displayed to the user.
So, what you need to do is define an intermediary that can be called with the specifics in your form that you want to validate which are also the same as in your web service. The intermediary can take one of two forms:
(probably the best):
public interface ErrorReturning {
public void getErrors(Errors errors);
}
(this can get ugly really fast if more than two states are added):
public interface ValidationObject {
public Errors getErrors(Errors errors);
public Object getResultOfWebServiceValidation();
}
I would suggest that the first approach be implemented. With your common validation, pass an object that can be used for web service validation directly, but allow it to implement the getErrors() method. This way, in your validator for Spring, inside your validation method you can simply call:
getCommonValidator().validate(partialObject).getErrors(errors);
Your web service would be based around calls to getCommonValidator().validate(partialObject) for a direct object to be used in the web service.
The second approach is like this, though the interface only allows for an object to be returned from the given object for a web service validation object, instead of the object being a usable web service validation object in and of itself.