golang singletons in beego - go

I'm trying out both Golang and Beego. I come from a Java/Spring background and I'm having a slightly difficult time implementing a singleton pattern for a webapp I'm developing. I have a controller (which I want to be a singleton) and I have a service within my controller (which I also want to be a singleton). I thought if I made my service a pointer, then I'd always use the same address (a singleton). This is not proving true.
My route looks like this
beego.Router("/", &controllers.SessionController{}, "get:Login")
My SessionController looks like this
type SessionController struct {
baseController
userService *services.UserService
}
func (this *SessionController) Prepare() {
this.baseController.Prepare()
if this.userService == nil {
beego.Info("user service was nil")
this.userService = factories.NewUserService()
}
}
My logs always show that the user service is nil upon each request. How can I get a single instance of my controller with a single (initialized only once) instance of my user service?

Make the user Service a singleton:
var globalUserService = factories.NewUserService()
type SessionController struct {
baseController
userService *services.UserService
}
func (this *SessionController) Prepare() {
this.baseController.Prepare()
if this.userService == nil {
beego.Info("user service was nil")
this.userService = globalUserService
}
}

1 of the creators of the Beego framework has mentioned to me that the framework creates a new instance of a controller per request, so it's not really possible to create a singleton :(

Here is everything you need to know about creating singleton in Golang
Singleton Pattern in Go
var instance *singleton
func GetInstance() *singleton {
if instance == nil {
instance = &singleton{} // <--- NOT THREAD SAFE
}
return instance
}
But that is not THREAD SAFE , you will need to use the Sync once
Example :-
import (
"sync"
)
type singleton struct {
}
var instance *singleton
var once sync.Once
func GetInstance() *singleton {
once.Do(func() {
instance = &singleton{}
})
return instance
}

Related

Providing Access to package level variable via public getter - How to return the instance?

I have a package level variable that I instantiate at the startup of the application. Even though it is declared to be package level, I need to access it from outside the package as well. To do that, I have a function that returns the variable.
package app
var myService MyService
type MyService interface {
DoThis()
DoThat()
}
func Initialize() {
// initialise other stuff
myService = initMyService()
}
func GetMyService() MyService {
return myService
}
Now from outside of the app package, when I need to do something with MyService, I do following.
ms := app.GetMyService()
ms.DoThis()
Here I have following questions.
Doesn't the GetMyService() function return copies of myService each time it is invoked?
If that is the case, if I return a pointer to the myService inside that function, does it solve that problem by returning a reference to the single myService instance that was initially instantiated?
var myService MyService here MyService is an interface. So you can implement it with pointer receiver methods or value receiver methods.
As go tour tour.golang.org/methods/8 mentioned,
There are two reasons to use a pointer receiver.
The first is so that the method can modify the value that its receiver
points to.
The second is to avoid copying the value on each method call. This can
be more efficient if the receiver is a large struct...
If you implement MyService with pointer receiver methods, It will not copy the receiver in every call.
And please refer golang.org/doc/faq Should I define methods on values or pointers?. There is a good explanation for it too.
sample implementation like below
type doer struct {
// any fields
}
func (d *doer) DoThis() {
// any implementation
fmt.Println(`do this`)
}
func (d *doer) DoThat() {
// any implementation
fmt.Println(`do that`)
}
func initMyService() MyService{
return &doer{
// init doer fields
}
}

Using Service methods inside Utils class [Spring and Kotlin]

I have faced a well-known scenarios whereby I really need to move a number of utilities private functions (that should not have been there in the first place) from my Service class to a utility class. My question is around using service methods in a utility class. I have attempted at the following refactoring:
class Utils(
val serviceIneed : ServiceIneed) {
companion object {
private val someMapper = ObjectMapperConfig.mapper
}
fun someUtility(): ResponseEntity<Any> {
// lots of stuff
return serviceIneed.someFunction()
}
}
Then this is the other service where I need to use the method I have moved to the newly created utility class:
class anotherService(
private val serviceIneed: ServiceIneed
) {
fun someMethod() {
// lots of things happening
val utilityUsage = Utils(serviceIneed).someUtility()
}
}
Is this the correct way to go about this? Can you recommend any approach on refactoring service classes in a way that only service-oriented methods and not helper ones remain in my Service class?
Thank you

How to mock a particular method of a spring bean

I have a spring bean with multiple APIs. Mocking the bean doesn't serve my purpose as I would like to verify fetchFromDb() called only once on multiple calls to getCachedData() with the same input. This is to make sure the result is cached.
Is it possible to mock fetchFromDb() on bean 'market' while calling getCachedData()?
Sample Class
#Configuration("market")
public class AllMarket {
#Autowired
private CacheManager cachedData;
public boolean getCachedData(LocalDate giveDate) {
//check if it exists in cache
if(Objects.nonNull(checkCache(giveDate)) {
return checkCache(giveDate);
}
//fetch from database
boolean bool = fetchFromDb(givenDate);
cacheData(giveDate, bool);
return bool;
}
public boolean checkCache(LocalDate giveDate) {
return cacheManager.getData(givenDate);
}
public boolean fetchFromDb(LocalDate givenDate) {
//return the data from database
}
public void cacheData(LocalDate givenDate, boolean bool) {
cacheManager.addToCache(givenDate, bool);
}
}
You can use Mockito.spy() for this kind of test. In this case you should spy your AllMarket instance and stub fetchFromDb. At the end you can Mockito.verify that fetchFromDb was called exactly once. It will look something like this:
AllMarket spy = spy(allMarket);
when(spy.fetchFromDb(givenDate)).thenReturn(true); //you have boolean as a return type
...
verify(spy, times(1)).fetchFromDb(givenDate);
For more information, you can see Official Mockito doc
Maybe mockito argument captor could asist you. It lets you to capture method input and how many times method was called, also may other functions. Please check https://www.baeldung.com/mockito-annotations.

Ninject Method Injection Redis

I am trying to use Ninject to manage my Redis dependencies on a ASP.NET Web Api project.
I do my binding like this:
var clientManager = new PooledRedisClientManager("localhost");
kernel.Bind<IRedisClientsManager>()
.ToMethod(ctx => clientManager)
.InSingletonScope();
kernel.Bind<IRedisClient>()
.ToMethod(k => k.Kernel.Get<IRedisClientsManager>()
.GetClient());
How can I subsequently get access to my redis client in other classes in the project?
I'm not familiar with Redis, so beware...
Now that you've got a binding, you can inject it into a constructor
public class Foo {
public Foo(IRedisClient redisClient) {...}
}
Or you can use a func to access/create it at a specific time:
public class Foo {
private readonly Func<IRedisClient> redisClientFunc;
public Foo(Func<IRedisClient> redisClientFunc)
{
this.redisClientFunc = redisClientFunc;
}
public void DoSomething()
{
IRedisClient client = this.redisClientFunc();
client.SayHello();
}
}
or, equivalently, you can use the ninject factory extension to achieve the same as the func, but with an interface, see https://github.com/ninject/ninject.extensions.factory/wiki. Both Func<> and interface factory need the factory extension.

How to use the Facade.Instance method without object construction?

I only recently completed a unit on software patterns and am now attempting to comprehend the PureMVC framework. One thing has got my stumped however, something which is simple to the gurus here.
I'm attempting to create an instance of the singleton Facade class. In the constructor, the comments state:
This IFacade implementation is a Singleton, so you should not call the constructor directly, but instead call the static Singleton Factory method Facade.Instance
How can you call the instance method when the Facade object has not even been created?
The Facade.Instance method looks like this:
public static IFacade Instance
{
get
{
if (m_instance == null)
{
lock (m_staticSyncRoot)
{
if (m_instance == null) m_instance = new Facade();
}
}
return m_instance;
}
}
You are accessing a static property. Static properties are part of the class definition, not class instances. To access a static member (property, field, method), simply use the class name dot member:
var myFacade = SomeClass.Instance;

Resources