简体   繁体   English

如何实现播放框架依赖注入为 singleton,如 spring 引导注释与配置和 Bean

[英]how to implement play framework dependency injection as singleton like spring boot annotation with Configuration and Bean

I wanna create a RateLimiter instance as singleton in play framework.我想在游戏框架中创建一个 RateLimiter 实例作为 singleton。 Here are the codes in Spring Boot.这是 Spring Boot 中的代码。

@Configuration
public class RateLimiterConfig {

  @Bean
  public RateLimiter rateLimiter() {
     return RateLimiter.create(0.1d);
  }
}

and then autowire this bean in the service that I want to use.然后在我想使用的服务中自动装配这个 bean。

private RateLimiter rateLimiter;

@Autowired
public void setRateLimiter(RateLimiter rateLimiter) {
    this.rateLimiter = rateLimiter;
}

but how can I acheive this in Play framework?但是我怎样才能在 Play 框架中实现这一点? I've created a class called RateLimitService and marked it as @Singleton.我创建了一个名为 RateLimitService 的 class 并将其标记为 @Singleton。 I want to prevent my api from duplicate requests and only allow 1 request in 100 seconds.我想防止我的 api 重复请求,并且只允许 100 秒内的 1 个请求。 (0.01 request per second) (每秒 0.01 个请求)

@Singleton
public class RateLimitService {

  public RateLimiter getRateLimiter () {
      return RateLimiter.create(0.01d);
  }
}

and registered it in my application.conf and in a module class which extends AbstractModule class and bind my RateLimitService class as EagerSingleton in the configure method like below并将其注册到我的 application.conf 和模块 class 中,该模块扩展了 AbstractModule class 并在配置方法中将我的 RateLimitService class 绑定为 EagerSingleton,如下所示

@Override
protected void configure() {
     
  ...... // ignore other modules

  bind(RateLimitService.class).asEagerSingleton();
}

and injected the RateLimitService in my controller like this并像这样在我的 controller 中注入 RateLimitService

@Inject
private RateLimitService rateLimitService;

However, when I run my application and call this method rateLimitService.getRateLimiter().tryAcquire();但是,当我运行我的应用程序并调用此方法rateLimitService.getRateLimiter().tryAcquire(); it will return a boolean to check if the request is in the period I set before.它将返回 boolean 以检查请求是否在我之前设置的时间段内。 But it always return a true for me and it seems that it always creates another rateLimitService instance whenever I call this api, because it does not block me.但它总是为我返回一个 true ,而且它似乎总是在我调用这个 api 时创建另一个 rateLimitService 实例,因为它不会阻止我。 I can make sure codes are right since it works in spring boot app.我可以确保代码是正确的,因为它在 spring 启动应用程序中工作。

Please help me and thank you in advance.请帮助我,并在此先感谢您。

You can do that using a provider您可以使用提供者来做到这一点

@Singleton
class RateLimitProvider @Inject() (configuration: Configuration) extends Provider[RateLimiter] {
  override def get(): RateLimiter = {
       // rate limit creation logic
    }
  }
}

in your binding do在你的绑定做

bind[RateLimiter].toProvider(classOf[RateLimitProvider])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM