标签: spring-boot

k3d 尝试拉取 Docker 镜像而不是使用本地镜像

只需在本地机器(Linux Mint 20.2)上研究K8S的核心即可。

使用以下命令在本地创建一个节点集群:

k3d集群创建mycluster

现在我想在容器中运行 spring boot 应用程序。
我构建本地图像:

库:0.1.0

这是摘自Deployment.yml

spec:
  terminationGracePeriodSeconds: 40
  containers:
    - name: 'library'
      image: library:0.1.0
      imagePullPolicy: IfNotPresent
Run Code Online (Sandbox Code Playgroud)

尽管图像已经构建:

docker images
REPOSITORY    TAG       IMAGE ID       CREATED             SIZE
library       0.1.0     254c13416f46   About an hour ago   462MB
Run Code Online (Sandbox Code Playgroud)

启动容器失败:

pod/library-867dfb64db-vndtj    Pulling image "library:0.1.0"
pod/library-867dfb64db-vndtj    Failed to pull image "library:0.1.0": rpc error: code = Unknown desc = failed to pull and unpack image "library:0.1.0": failed to resolve reference "library:0.1.0": failed to do request: Head "https://...com/v2/library/manifests/0.1.0": x509: certificate …
Run Code Online (Sandbox Code Playgroud)

linux docker spring-boot kubernetes k3d

4
推荐指数
1
解决办法
4293
查看次数

将 spring-boot-starter-parent 升级到版本 2.6.6 后,Java Spring Boot java.lang.NoClassDefFoundError

我有一个 Spring Boot 应用程序,一直在使用 spring-boot-starter-parent 版本 2.3.9.RELEASE。由于存在漏洞,我们需要更新应用程序以使用版本 2.6.6。

升级后,我的一些单元测试出现错误:

testGetDiscount(com.ally.abmt.integrationapi.util.IntegrationApiUtilTest)  Time elapsed: 0 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/boot/model/naming/CamelCaseToUnderscoresNamingStrategy
Caused by: java.lang.NoClassDefFoundError: …
Run Code Online (Sandbox Code Playgroud)

java spring-boot

4
推荐指数
1
解决办法
1万
查看次数

如何使用 Dockerfile 将 Maven 依赖项存储在 docker 映像内

所以我正在制作一个 Spring Boot 应用程序,我应该将其放入 docker 容器中并运行,并且我想使用 docker 文件构建整个映像。
我正在使用这个 dockerFile:

FROM openjdk:8-jdk-alpine
ADD . /analytics-service
WORKDIR /analytics-service
ENTRYPOINT ./mvnw spring-boot:run 
Run Code Online (Sandbox Code Playgroud)

当我创建图像时,它只是复制文件,并且只有在我运行它之后,它才开始下载所有 Maven 依赖项。鉴于我将运行一些容器,这需要一段时间。那么我该怎么做呢?我希望它在创建图像时获取所有依赖项,因此当我创建容器时它不会开始下载。

java docker spring-boot docker-compose

4
推荐指数
1
解决办法
4141
查看次数

将HandlerInterceptor迁移到Spring boot 2.6

我为 Spring 2.4 实现了这个旧代码

public class Interceptor extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {
    ........
    return super.preHandle(request, response, handler);
  }
}
Run Code Online (Sandbox Code Playgroud)

我将代码迁移到Spring 2.6:

public class Interceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {
    ......................
    return HandlerInterceptor.super.preHandle(request, response, handler);
  }
}
Run Code Online (Sandbox Code Playgroud)

我明白了Cannot resolve method 'preHandle' in 'Object',所以我将代码更改为HandlerInterceptor.super.preHandle(request, response, handler);

以这种方式编辑代码是否正确:HandlerInterceptor.super.preHandle(request, response, handler);或者应该以其他方式编辑?

java spring spring-boot

4
推荐指数
1
解决办法
2073
查看次数

如何修复 org.hibernate.LazyInitializationException:未能延迟初始化角色集合:信息,无法初始化代理 - 无会话

我的 Spring Boot 项目中有一个客户和一个客户信息实体。他们有一对多的关系。

\n
@Data\n@Builder\n@Entity\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = "customer")\npublic class Customer implements Serializable{\n\n    @Serial\n    private static final long serialVersionUID = 1L;\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long serialNumber;\n\n    private Long customerId;\n    private String name;\n\n\n\n    @Column(name = "session_id", length = 128)\n    private String sessionId;\n\n    @JsonManagedReference("customer-customer_info")\n    @OneToMany(targetEntity = CustomerInfo.class, mappedBy="Customer", cascade = CascadeType.ALL)\n    private List<CustomerInfo> customerInfoList;\n\n}\n\n@Data\n@Builder\n@Entity\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = "customer_info")\npublic class CustomerInfo implements Serializable{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private Long CustomerInfoId;\n\n    @ManyToOne\n    @JsonBackReference("customer-customer_info")\n    @ToString.Exclude\n    @JoinColumn(name="customer_session_id", nullable=false, referencedColumnName = "session_id")\n    private Customer customer;\n\n    private String metaKey;\n\n …
Run Code Online (Sandbox Code Playgroud)

java hibernate lazy-loading lazy-initialization spring-boot

4
推荐指数
1
解决办法
3万
查看次数

如何为特定的声明结构配置 JwtAuthenticationConverter?

我有一个 JWT,可以在特定声明下找到角色。该声明处于嵌套结构中。如何告诉 JwtAuthenticationConverter 查找特定路径下的角色?

作为授权服务器,我使用 Keycloak。可以为角色添加映射器。但我现在想排除这种可能性,因为目标是找到特定声明下的角色。

这是我解码的 JWT。角色“user-role”应位于声明下:“resource_access”->“user”->“roles”:

  "resource_access": {
    "admin": {
      "roles": [
        "admin-role"
      ]
    },
    "user": {
      "roles": [
        "user-role"
      ]
    },
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    }
  },
Run Code Online (Sandbox Code Playgroud)

这是我的 JwtAuthenticationConverter 配置:

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(HttpSecurity http) throws Exception
    {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
    }

    private static JwtAuthenticationConverter jwtAuthenticationConverter()
    {
        var jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("resource_access.user.roles");
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
        var jwtAuthenticationConverter = new JwtAuthenticationConverter(); …
Run Code Online (Sandbox Code Playgroud)

spring-security oauth-2.0 jwt spring-boot keycloak

4
推荐指数
1
解决办法
1万
查看次数

Spring Boot + Flyway + Testcontainers(mariaDB):表“xxxx”不存在

我在 Spring Boot 项目中使用 Testcontainers 和 mariaDB 数据库进行单元测试。我最近将Spring Boot从2.4.4升级到2.6.6,发现单元测试开始失败。在发生 Flyway 迁移(创建数据库模式)后,再次创建了 Testcontainers(?)。

\n

我有点困惑,想知道是否需要设置特定配置才能使单元测试再次工作。

\n

依赖关系如下

\n
plugins {\n    ...\n    id 'org.springframework.boot' version '2.6.6'\n    id "org.flywaydb.flyway" version "8.4.2"\n    ...\n}\n\ndependencies {\n    ...\n    testCompileOnly 'junit:junit:4.13.2'\n    testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.8.2'\n    implementation  "org.flywaydb:flyway-core:8.1.0"\n    implementation 'org.mariadb.jdbc:mariadb-java-client:3.0.4'\n    implementation "org.jooq:jooq:3.16.5"\n    testImplementation "org.testcontainers:mariadb:1.16.2"\n    ....\n
Run Code Online (Sandbox Code Playgroud)\n

配置如下

\n
spring.datasource.url=jdbc:tc:mariadb:10.5:///\nspring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver\nspring.datasource.username=""\nspring.datasource.password=""\n\nspring.jooq.sql-dialect=MARIADB\n\nspring.flyway.enabled=true\nspring.flyway.locations=filesystem:./src/main/resources/db/migration\nspring.flyway.url=jdbc:tc:mariadb:10.5:///\nspring.flyway.baseline-on-migrate=true\n\n# logging\nlogging.level.org.hibernate.SQL=DEBUG\nlogging.level.org.hibernate.type=TRACE\n
Run Code Online (Sandbox Code Playgroud)\n

日志消息如下

\n
INFO 49309 --- [    Test worker] c.a.a.m.r.MyUnitTest   : Starting MyUnitTest using Java 11.0.11 on xxxxxxx with PID 49309 (started by user.name in /Volumes/code/sample/sample)\nINFO 49309 --- [    Test worker] …
Run Code Online (Sandbox Code Playgroud)

junit4 mariadb flyway spring-boot testcontainers

4
推荐指数
1
解决办法
4150
查看次数

优化 Spring Boot 中的数据获取和插入

我的 CSV 文件中有 270000 条记录,其中包含 user_id、book_ISBN 和 book_ rating 列,我需要将这些记录插入到多对多表中。我使用 openCSV 库解析数据,结果是一个列表。

public List<UserRatingDto> uploadRatings(MultipartFile file) throws IOException{
        BufferedReader fileReader = new BufferedReader(new
                InputStreamReader(file.getInputStream(), "UTF-8"));

        List<UserRatingDto> ratings = new CsvToBeanBuilder<UserRatingDto>(fileReader)
                .withType(UserRatingDto.class)
                .withSeparator(';')
                .withIgnoreEmptyLine(true)
                .withSkipLines(1)
                .build()
                .parse();
        return ratings;
    }
Run Code Online (Sandbox Code Playgroud)

这不存在性能问题,解析大约需要 1 分钟。但是,为了将它们插入到表中,我需要从数据库中获取书籍和用户以形成关系,我尝试使该方法与 @Async 注释异步,我尝试了并行流,我尝试将对象放入放入堆栈并使用 saveAll() 批量插入,但仍然花费太多时间。

 public void saveRatings(final MultipartFile file) throws IOException{
        List<UserRatingDto> userRatingDtos = uploadRatings(file);

        userRatingDtos.parallelStream().forEach(bookRating->{
            UserEntity user = userRepository.findByUserId(bookRating.getUserId());
            bookRepository.findByISBN(bookRating.getBookISBN()).ifPresent(book -> {
                BookRating bookRating1 = new BookRating();
                bookRating1.setRating(bookRating.getBookRating());
                bookRating1.setUser(user);
                bookRating1.setBook(book);
                book.getRatings().add(bookRating1);
                user.getRatings().add(bookRating1);
                bookRatingRepository.save(bookRating1);
            });

        });
}
Run Code Online (Sandbox Code Playgroud)

这就是我现在所拥有的,有什么我可以改变以使其更快吗?

database bulkinsert sql-insert spring-data-jpa spring-boot

4
推荐指数
1
解决办法
4319
查看次数

Kotlin spring boot @RequestBody 验证未触发

我在使用验证 @RequestBody 的项目上遇到问题

implementation("org.springframework.boot:spring-boot-starter-validation")
Run Code Online (Sandbox Code Playgroud)

我的 DTO 如下所示:

import javax.validation.constraints.Email
import javax.validation.constraints.Pattern

class LoginDto(
    @Email
    val email: String,

    @Pattern(regexp = Constants.PASSWORD_REGEX)
    val password: String
)
Run Code Online (Sandbox Code Playgroud)

控制器看起来像这样:

import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.validation.Valid

@RestController
@Validated
class AuthController(private val authService: AuthService) {

    @PostMapping("login")
    fun login(@Valid @RequestBody loginDto: LoginDto): LoginResponse {
        return authService.login(loginDto)
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试传递无效数据,验证不会出现错误:

{
    "password":"hello",
    "email":"dfdfdfdf"
}
Run Code Online (Sandbox Code Playgroud)

我没有收到错误,我使用 Exposed 而不是 jpa,但我认为这与问题无关

spring kotlin spring-boot spring-validation

4
推荐指数
1
解决办法
1798
查看次数

java.net.UnknownHostException:在 Spring Boot 和 Cloud 中进行 4 次查询后无法解析“库存服务”

我使用Spring Boot v2.7.0和 Spring Cloud 堆栈来执行服务间通信。我看到了一些解决方案,例如:https://github.com/spring-cloud/spring-cloud-gateway/issues/2091,但它们都不适合我。

我在这里更新了代码:https://github.com/javaHelper/Spring-Boot-Microservices-sai-youtube/tree/main/3.Using-service-discovery

错误:

2022-06-10 09:31:26.600 ERROR 9506 --- [nio-8090-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.reactive.function.client.WebClientRequestException: Failed to resolve 'inventory-service' after 4 queries ; nested exception is java.net.UnknownHostException: Failed to resolve 'inventory-service' after 4 queries ] with root cause

java.net.UnknownHostException: Failed to resolve 'inventory-service' after 4 queries 
    at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1047) ~[netty-resolver-dns-4.1.77.Final.jar:4.1.77.Final]
    at io.netty.resolver.dns.DnsResolveContext.tryToFinishResolve(DnsResolveContext.java:1000) ~[netty-resolver-dns-4.1.77.Final.jar:4.1.77.Final]
    at io.netty.resolver.dns.DnsResolveContext.query(DnsResolveContext.java:418) ~[netty-resolver-dns-4.1.77.Final.jar:4.1.77.Final]
    at …
Run Code Online (Sandbox Code Playgroud)

java spring-boot microservices spring-cloud

4
推荐指数
1
解决办法
2万
查看次数