在这些日子里,我正在尝试编写一些代码来体验Spring 5中的Spring反应特性和kotlin扩展,并且我还准备了一个gradle Kotlin DSL build.gradle.kt来配置gradle构建.
它build.gradle.kt是由http://start.spring.io生成的Spring Boot模板代码转换而来.
但是ext在buildscriptGradle中无法检测到.
buildscript {
ext { }
}
Run Code Online (Sandbox Code Playgroud)
这ext将导致Gradle构建错误.
为了使变量进入classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")并compile("org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlinVersion")工作,我以艰难的方式添加了变量.
val kotlinVersion = "1.1.4"
val springBootVersion = "2.0.0.M3"
Run Code Online (Sandbox Code Playgroud)
但我必须在全球顶级位置声明它们并将其复制到buildscript.
代码:https://github.com/hantsy/spring-reactive-sample/blob/master/kotlin-gradle/build.gradle.kts
是否有优雅的ext工作方法?
更新:有一些丑陋的方法:
从Gradle Kotlin DSL示例https://github.com/gradle/kotlin-dsl/tree/master/samples/project-properties中,声明了gradel.properties中的属性.
kotlinVersion = 1.1.4
springBootVersion = 2.0.0.M3
Run Code Online (Sandbox Code Playgroud)
并在build.gradle.kts中使用它.
buildScript{
val kotlinVersion by project
}
val kotlinVersion by project //another declare out of buildscript block.
Run Code Online (Sandbox Code Playgroud)与上面类似,在buildScript块中声明它们:
buildScript{ …Run Code Online (Sandbox Code Playgroud)我尝试将我的 data-mongo 示例项目升级到 Spring Boot 2.6.0。有一个设计用于针对 Testcontainers 运行的测试,我还包含了用于其他测试的嵌入式 mongo dep,因此我必须排除嵌入式 mongo 的自动配置,以确保此测试在 Docker/testcontainers 上运行。
以下配置适用于 Spring Boot 2.5.6。
@DataMongoTest
@ContextConfiguration(initializers = {MongodbContainerInitializer.class})
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@Slf4j
@ActiveProfiles("test")
public class PostRepositoryTest {}
Run Code Online (Sandbox Code Playgroud)
但是升级到 Spring Boot 2.6.0 并运行应用程序后,我得到了这样的异常。
[ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: o
rg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'embeddedMongoServer' defined in class path resource [org/springframework/boot/autoconfig
ure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]: Unsatisfied dependency expressed through method 'embeddedMongoServer' parameter 0; nested exception is org.springframework.bea
ns.factory.BeanCreationException: Error creating …Run Code Online (Sandbox Code Playgroud) 我尝试使用KinD作为 Minikube 的替代品在我的本地计算机中引导 K8S 集群。
\n集群创建成功。
\n但是当我尝试从映像创建一些 Pod/部署时,它失败了。
\n$ kubectl run nginx --image=nginx\n$ kubectl run hello --image=hello-world\nRun Code Online (Sandbox Code Playgroud)\n几分钟后,用于get pods获取失败状态。
$ kubectl get pods\nNAME READY STATUS RESTARTS AGE\nhello 0/1 ImagePullBackOff 0 11m\nnginx 0/1 ImagePullBackOff 0 22m\nRun Code Online (Sandbox Code Playgroud)\n恐怕这是中国的另一个全球防火墙问题。
\nkubectl describe pods/nginx\nName: nginx\nNamespace: default\nPriority: 0\nNode: dev-control-plane/172.19.0.2\nStart Time: Sun, 30 Aug 2020 19:46:06 +0800\nLabels: run=nginx\nAnnotations: <none>\nStatus: Pending\nIP: 10.244.0.5\nIPs:\n IP: 10.244.0.5\nContainers:\n nginx:\n Container ID:\n Image: nginx\n Image ID:\n Port: <none>\n Host Port: <none>\n State: …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 Gitlab CI yaml 配置文件中的作业之间添加需求。
stages:
- build
- test
- package
- deploy
maven-build:
stage: build
only:
- merge_requests
- master
- branches
...
test:
stage: test
needs: [ "maven-build" ]
only:
- merge_requests
- master
...
docker-build:
stage: package
needs: [ "test" ]
only:
- master
...
deploy-stage:
stage: deploy
needs: [ "docker-build" ]
only:
- master
...
deploy-prod:
stage: deploy
needs: [ "docker-build" ]
only:
- master
when: manual
...
Run Code Online (Sandbox Code Playgroud)
我已经使用 GitLab CI 在线 lint 工具来检查我的语法,它是正确的 …
在传统的Spring Web应用程序,很容易得到一个SecurityContext从SecurityContextHolder,但是当我用spring-security-webflux一个弹簧webflux申请(春季安全5.0.O.M3),似乎春季安全没有存储SecurityContext到SecurityContextHolder的每一个请求。
或者换句话说,是否有一种简单的方法可以在 WebHanlder/Controllers 之外获取当前的身份验证信息?我想实现AuditorAware接口以获取 Spring Data MongoDB 的审计(自动填充当前用户)。
更新:Spring Security 5.0.0.RELEASE 提供了一个ReactiveSecurityContextHolder归档这个目的。
在Spring 5.0.0.RC4参考文档中,它说:
Publisher或Flow.Publisher - 支持实现Reactive Streams Publisher的任何类型.
https://docs.spring.io/spring/docs/5.0.0.RC4/spring-framework-reference/reactive-web.html#webflux
但是当我创建一个基于Spring 5.0.0.RC4的简单项目时,我Flow.Publisher在控制器中返回时失败了.似乎Flow.Publisher杰克逊无法将其序列化.
org.springframework.core.codec.CodecException: Type definition error: [simple type, class java.util.concurrent.ForkJoinPool$DefaultForkJoinWorkerThreadFactory]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.util.concurrent.ForkJoinPool$DefaultForkJoinWorkerThreadFactory and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.concurrent.SubmissionPublisher["executor"]->java.util.concurrent.ForkJoinPool["factory"])
at org.springframework.http.codec.json.AbstractJackson2Encoder.encodeValue(AbstractJackson2Encoder.java:132)
at org.springframework.http.codec.json.AbstractJackson2Encoder.lambda$encode$0(AbstractJackson2Encoder.java:96)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107)
at reactor.core.publisher.FluxJust$WeakScalarSubscription.request(FluxJust.java:91)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:156)
at org.springframework.http.server.reactive.ChannelSendOperator$WriteBarrier.onSubscribe(ChannelSendOperator.java:143)
at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:90)
at reactor.core.publisher.FluxJust.subscribe(FluxJust.java:68)
at reactor.core.publisher.FluxMapFuseable.subscribe(FluxMapFuseable.java:63)
at org.springframework.http.server.reactive.ChannelSendOperator.subscribe(ChannelSendOperator.java:76)
at reactor.core.publisher.MonoOnErrorResume.subscribe(MonoOnErrorResume.java:44)
at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:150)
at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1068)
at reactor.core.publisher.MonoFlatMap$FlatMapInner.onNext(MonoFlatMap.java:241)
at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:72)
at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:198) …Run Code Online (Sandbox Code Playgroud) 我按照Spring Security 5.0官方参考文档和示例代码oauth2login在我的项目中设置OAuth2/OIDC身份验证,但它失败了,当我启动我的应用程序时出现以下异常mvn spring-boot:run.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository'
defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2ClientRegistrationRepositoryConfiguration.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]:
Factory method 'clientRegistrationRepository' threw exception;
nested exception is java.lang.IllegalArgumentException: authorizationGrantType cannot be null
Run Code Online (Sandbox Code Playgroud)
我用的是由Spring启动提供的默认配置,只是增加了一些基本的依赖关系到项目,如spring-security-config,spring-security-oauth2-client,spring-security-oauth2-jsoe等.
更新:
我找到了原因,对于自定义OAuth2提供程序,例如Gitlab,我必须添加grant type,redirectUritemplate,scope,clientName等,但OpenID Connect规范有一个配置端点协议,例如:https://gitlab.com/ .well-known/openid-configuration,有可能让Spring Security自动读取这些信息吗?
我正在尝试将Quarkus 顶点示例转换为纯Vertx 4.0,但遇到了问题。
在 Quarkus 中,可以轻松自定义 Jackson ObjectMapper 来序列化或反序列化 HTTP 消息。
@ApplicationScoped
public class CustomObjectMapper implements ObjectMapperCustomizer {
@Override
public void customize(ObjectMapper objectMapper) {
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
objectMapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
objectMapper.registerModule(module);
}
}
Run Code Online (Sandbox Code Playgroud)
而在Vertx中,如何ObjectMapper优雅地定制呢?我的目的是注册一个自定义ObjectMapper而不是内置自定义,因此在使用 时Json.encode,它将使用我的自定义objectMapper。
在我的 Vertx 示例中,Json.encode将使用内置函数objectMapper将 Java 8 DateTime 序列化为 int 数组而不是 ISO 日期字符串。
我创建了一个 NestJS 并使用 TypeORM 作为 RDBMS(我在项目中使用了 postgres)。
Post是一个@Entity类,PostRepository是 的一个Repository类Post。
我试图创建OnModuleInit服务来初始化一些数据。
@Injectable()
export class PostsDataInitializer implements OnModuleInit {
private data: Post[] = [
{
title: 'Generate a NestJS project',
content: 'content',
},
{
title: 'Create GrapQL APIs',
content: 'content',
},
{
title: 'Connect to Postgres via TypeORM',
content: 'content',
},
];
constructor(private readonly postRepository: PostRepository) {}
async onModuleInit(): Promise<void> {
await this.postRepository.manager.transaction(async (manager) => {
// NOTE: you must perform …Run Code Online (Sandbox Code Playgroud) 我添加了一项OnMoudleInit服务来初始化 NestJS 应用程序中的一些示例数据。
TypeORM 提供了多种将查询包装到单个事务中的方法。
我尝试使用EntityManager.transaction来包装操作。
await this.manager.transaction(async (manager) => {
// NOTE: you must perform all database operations using the given manager instance
// it's a special instance of EntityManager working with this transaction
// and don't forget to await things here
const del = await manager.delete(PostEntity, {});
console.log('posts deleted: ', del.affected);
const userDel = await manager.delete(UserEntity, {});
console.log('users deleted: ', userDel.affected);
const user = new UserEntity();
Object.assign(user, {
firstName: 'hantsy',
lastName: 'bai',
email: 'hantsy@gmail.com', …Run Code Online (Sandbox Code Playgroud) spring ×4
nestjs ×2
spring-boot ×2
typeorm ×2
build.gradle ×1
docker ×1
gitlab ×1
gitlab-ci ×1
gradle ×1
java ×1
java-9 ×1
kotlin ×1
kubernetes ×1
oauth-2.0 ×1
spring-data ×1
spring-data-mongodb-reactive ×1
vert.x ×1