Execution Context关于在Scala中执行期货的最佳/如何/最佳用途以及如何配置调度程序,存在很多问题.我仍然无法找到更长的列表,其中包含优缺点和配置示例.
我能找到的最好的是Akka文档:http://doc.akka.io/docs/akka/snapshot/scala/dispatchers.html和Play Documentation https://www.playframework.com/documentation/2.5.x/ThreadPools.
我想问一下除了scala.concurrent.ExecutionContext.Implicits.global你在日常开发生活中使用的Akka默认配置,当你使用它们时有什么配置,以及它们的优点和缺点.
以下是我已经拥有的一些内容:
scala.concurrent.ExecutionContext.Implicits.global在不确定时使用
使用方便
可能会耗尽你所有的CPU
更多信息:http://www.scala-lang.org/api/2.11.5/index.html#scala.concurrent.ExecutionContext
ExecutionContext.fromExecutor(new ForkJoinPool(1))play.api.libs.concurrent.Execution.Implicits._scala.concurrent.ExecutionContext.Implicits.global使用Play共享
更多信息:https://www.playframework.com/documentation/2.5.x/ThreadPools
ExecutionContext.fromExecutor(new ForkJoinPool(n)) based on an separated dispatcher . Thanks to Sergiy Prydatchenko
Run Code Online (Sandbox Code Playgroud) 我试图将JSF ViewScoped bean作为ManagedProperty注入到RequestScoped bean中,该bean实现了javax.faces.validator.Validator.但是总是会注入ViewScoped bean的新副本.
ViewScoped Bean
@ViewScoped
@ManagedBean
public class Bean {
private Integer count = 1;
private String field2;
public String action(){
++count;
return null;
}
public String anotherAction(){
return null;
}
//getter and setter
}
Run Code Online (Sandbox Code Playgroud)
验证器
@RequestScoped
@ManagedBean
public class SomeValidator implements Validator {
public void validate(FacesContext context, UIComponent comp, Object value)
throws ValidatorException {
//logging bean.getCount() is always one here. Even after calling ajax action a few times
}
@ManagedProperty(value = "#{bean}")
private Bean bean;
} …Run Code Online (Sandbox Code Playgroud) 以下代码成功,但是有更好的方法做同样的事情吗?也许是案例类特有的东西?在下面的代码中,对于我的简单案例类中String类型的每个字段,代码遍历我的案例类的实例列表,并查找该字段的最长字符串的长度.
case class CrmContractorRow(
id: Long,
bankCharges: String,
overTime: String,
name$id: Long,
mgmtFee: String,
contractDetails$id: Long,
email: String,
copyOfVisa: String)
object Go {
def main(args: Array[String]) {
val a = CrmContractorRow(1,"1","1",4444,"1",1,"1","1")
val b = CrmContractorRow(22,"22","22",22,"55555",22,"nine long","22")
val c = CrmContractorRow(333,"333","333",333,"333",333,"333","333")
val rows = List(a,b,c)
c.getClass.getDeclaredFields.filter(p => p.getType == classOf[String]).foreach{f =>
f.setAccessible(true)
println(f.getName + ": " + rows.map(row => f.get(row).asInstanceOf[String]).maxBy(_.length))
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
bankCharges: 3
overTime: 3
mgmtFee: 5
email: 9
copyOfVisa: 3
Run Code Online (Sandbox Code Playgroud) 我有一个Play Framework应用程序,版本2.4迁移到2.5,一切都完成了!但在使用BodyParser的自定义操作中抛出错误,
def isAuthenticatedAsync[A](parser: BodyParser[A])(f: => Long => Request[A] => Future[Result]) = {
Security.Authenticated(userId, onUnauthorized) { user =>
Action.async(parser)(request => f(user)(request))
}
Run Code Online (Sandbox Code Playgroud)
}
用这个:
def upload = isAuthenticatedAsync(parse.maxLength(5 * 1024 * 1024, parse.multipartFormData)) { userId => request =>
//Logger.info(s"")
request.body match {
case Left(MaxSizeExceeded(length)) => Future(BadRequest(Json.toJson(ResultTemp("Your file is too large, we accept just " + length + " bytes!"))))
case Right(multipartForm) =>
Run Code Online (Sandbox Code Playgroud)
抛出错误:
could not find implicit value for parameter mat: akka.stream.Materializer
Run Code Online (Sandbox Code Playgroud)
[error] def …
问题是我的实体中有两个袋子,我想在我的jsf前端显示(后面的Spring,所以没有延迟加载).所以我必须急切地获取它们以在这样的列表中显示信息:
将两个列表都置于渴望之中并不起作用.所以我尝试了一下fetch join.它允许我获取一个列表,但是当我添加第二个列表时,我得到了已知的"无法获取多个包"错误.
Hibernate可以在查询中处理两个fetch连接吗?
public class PointOfInterest
@OneToMany(mappedBy="poi")
private List<PointOfInterestLabel> labels = new ArrayList<PointOfInterestLabel>();
@ManyToMany
private List<Tag> tags = new ArrayList<Tag>();
Run Code Online (Sandbox Code Playgroud)
我的获取加入:
SELECT DISTINCT p from PointOfInterest p
left join fetch p.labels
left join fetch p.tags WHERE p.figure = :figure
Run Code Online (Sandbox Code Playgroud)
在启动时,我的hibernate工厂的创建失败了:
Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
at org.hibernate.loader.BasicLoader.postInstantiate(BasicLoader.java:94)
at org.hibernate.loader.hql.QueryLoader.<init>(QueryLoader.java:123)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98)
at org.hibernate.impl.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:557)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:422)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:883)
... 55 more
Run Code Online (Sandbox Code Playgroud) 我在Play中创建了一个允许用户上传文件的最小网站.虽然涉及的代码相当简单,但我找不到编译错误的原因:
Cannot write an instance of views.html.uploadFile.type to HTTP response. Try to define a Writeable[views.html.uploadFile.type]
Run Code Online (Sandbox Code Playgroud)
以下是内容views.uploadFile.scala.html:
@helper.form(action = routes.FileUpload.handleUpload, 'enctype -> "multipart/form-data") {
File to upload: <input type="file" name="uploadedFile">
<div> <input type="submit"> </div>
}
Run Code Online (Sandbox Code Playgroud)
这是控制器显示文件上传表单并处理上传的文件:
package controllers
import play.api.i18n.{MessagesApi, I18nSupport}
import play.api.mvc._
import javax.inject.Inject
class FileUpload @Inject()(val messagesApi: MessagesApi) extends Controller with I18nSupport {
def uploadForm = Action {
Ok(views.html.uploadFile)
}
def handleUpload = Action(parse.multipartFormData) { request =>
import java.io.File
request.body.file("uploadedFile") match {
case Some(file) =>
val fileName …Run Code Online (Sandbox Code Playgroud) 我正在尝试基于一组可能设置或可能未设置的参数来实现返回过滤结果的方法.似乎没有条件地链接多个过滤器,即从一个过滤器开始......
val slickFlights = TableQuery[Flights]
val query = slickFlights.filter(_.departureLocation === params("departureLocation").toString)
Run Code Online (Sandbox Code Playgroud)
有条件地在查询中添加另一个过滤器(如果它存在于params的Map中)似乎不起作用......
if (params.contains("arrivalLocation")) {
query.filter(_.arrivalLocation === params("arrivalLocation").toString)
}
Run Code Online (Sandbox Code Playgroud)
可以通过其他方式使用Slick完成这种条件过滤吗?
我遇到过MaybeFilter:https://gist.github.com/cvogt/9193220 ,这似乎是处理这个问题的一个不错的方法.但它似乎不适用于Slick 3.x.
根据Hüseyin的建议,我也尝试了以下方法:
def search(departureLocation: Option[String], arrivalLocation: Option[String]) = {
val query = slickFlights.filter(flight =>
departureLocation.map {
param => param === flight.departureLocation
})
Run Code Online (Sandbox Code Playgroud)
slickFlightsTableQuery对象在哪里val slickFlights = TableQuery[Flights].但是,这会产生以下编译错误:
value === is not a member of String
Run Code Online (Sandbox Code Playgroud)
Intellij还抱怨= =是一个未知的符号.不适用于==.
我想监视我的postgresql实例的所有查询.以下这些步骤,我创建了一个自定义的数据库参数组,设置log_statement到all和log_min_duration_statement到1,应用的参数组到我的实例,并重新启动它.然后我向POST实例发出了一个请求,但是在Recent Events & Logs我的实例的选项卡中找不到查询记录.但是,执行SELECT * FROM table查询psql表明资源已创建且后期请求有效.为了看到日志,我错过了什么?
我最近开始使用 Scala 和 Play Framework,并且刚刚将我一直在开发的服务升级到 Play 2.4.3。我的最终目标是创建一个夜间进程,在我的播放应用程序中启动一个服务方法,以便通过方法调用来调度事件,我当前正在使用 Actor 调用该方法。
我的基本想法是通过一个 Global.scala 文件来覆盖 onStart,但后来我看到了关于不再使用 GlobalSettings 的 play 文档(https://www.playframework.com/documentation/2.4.x ) /GlobalSettings)并一直试图将其转移到注入依赖方法。
这是我到目前为止所拼凑的内容:
模块代码:
import javax.inject._
import com.myOrganization.myPackage.Actors.ScheduleActor
import play.api.libs.concurrent.AkkaGuiceSupport
import play.libs.Akka
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import akka.actor.{ActorRef, ActorSystem}
import scala.concurrent.duration._
import play.Application
import com.google.inject.AbstractModule
@Singleton
class NightlyEvalSchedulerStartup @Inject()(system: ActorSystem, @Named("ScheduleActor") scheduleActor: ActorRef) {
Akka.system.scheduler.schedule(10.seconds, 20.seconds, scheduleActor, "ScheduleActor")
}
class ScheduleModule extends AbstractModule with AkkaGuiceSupport {
def configure() = {
bindActor[ScheduleActor]("ScheduleActor")
bind(classOf[NightlyEvalSchedulerStartup]).asEagerSingleton
}
}
Run Code Online (Sandbox Code Playgroud)
演员等级:
import akka.actor.{Actor, Props}
import com.myOrganization.myPackage.services.MySchedulingService
object ScheduleActor { …Run Code Online (Sandbox Code Playgroud) 我需要从中调用我的Web应用程序的URL.例如: - 如果从stackoverflow.com链接到我的网站foo.com,我需要web应用程序(托管bean)中的stackoverflow链接.
所有人都非常感谢,谢谢.
scala ×6
akka ×2
java ×2
amazon-rds ×1
case-class ×1
concurrency ×1
fetch ×1
file-upload ×1
hibernate ×1
join ×1
jpa-2.0 ×1
jsf ×1
jsf-2 ×1
postgresql ×1
reflection ×1
shapeless ×1
slick ×1
spray ×1