为了优化sql请求,我制作了一个聚合其他服务消耗的服务,以避免不必要的调用。 (我的网络应用程序的某些页面每天被调用数百万次,因此我希望在每个请求上尽可能多次地重用数据库查询的结果)
我创建的解决方案是这样的:
我的服务有 @RequestScope 而不是默认范围(单例)
在我的服务中
@Service
@RequestScope
public MyService {
private int param;
@Autowired
private OtherService otherService;
@Autowired
private OtherService2 otherService2;
private List<Elements> elements;
private List<OtherElements> otherElements;
public void init(int param) {
this.param = param;
}
public List<Elements> getElements() {
if(this.elements == null) {
//Init elements
this.elements = otherService.getElements(param);
}
return this.elements;
}
public List<OtherElements> getOtherElements() {
if(this.otherElements == null) {
//Init otherElements
this.otherElements = otherService2.getOtherElements(param);
}
return this.otherElements;
}
public String getMainTextPres() {
//Need to use lElements;
List<Elements> elts = this.getElements();
....
return myString;
}
public String getSecondTextPres() {
//Need to use lElements;
List<Elements> elts = this.getElements();
//Also Need to use lElements;
List<OtherElements> otherElts = this.getOtherElements();
....
return myString;
}
}
在我的 Controller 中:
public class myController {
@Autowired MyService myService;
@RequestMapping...
public ModelAndView myFunction(int param) {
myService.init(param);
String mainTextPres = myService.getMainTextPres();
String secondTextPres = myService.getSecondTextPres();
}
@OtherRequestMapping...
public ModelAndView myFunction(int param) {
myService.init(param);
String secondTextPres = myService.getSecondTextPres();
}
}
当然,我简化了我的示例,因为 myService 使用了很多其他元素,并且我保护了他的成员属性的初始化
此方法的优点是仅在需要时才延迟加载属性。 如果我的项目中的某个地方(在相同或其他 Controller 中)我只需要 SecondTextPres,那么调用“getSecondTextPres”将初始化两个列表,这在我的示例中不是这种情况,因为调用“getMainTextPres”时第一个列表已初始化。
我的问题是:
- 您对这种做事方式有何看法?
- 由于我根据每个请求实例化我的服务,可能会遇到性能问题吗?
非常感谢!
朱利安
最佳答案
我认为你的想法不会成功。如果您调用相同或不同的 Controller ,这将是不同的请求 - 在这种情况下,将创建新的 bean(元素和其他元素再次为空)。
您是否考虑过缓存? Spring 有很好的支持,你可以定义缓存过期等
关于java - Spring 4 @Service 和 @RequestScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39701043/