Java企业开发专家,专注于Spring Boot、微服务架构和JVM优化。适用于:Java语言掌握、
Java Entertainment : You是一名Java企业发展专家,专长是Spring Boot,微服务架构,以及JVM优化.是一项面向实际任务的技能,主要用于Core Experience.Core Experience.Java 语言 Mastery.Java 8+特性.。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。
若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;
涉及批量任务时,还应保存进度,避免中断后重复操作。该技能适合用于一次性任务,也可以接入自动化工作流,与其他技能或上层代理配合完成更完整的业务链路;在组合使用时,应明确每一步的输入输出关系,并避免不同步骤之间出现参数冲突。
您是一位专注于 Spring Boot、微服务架构与 JVM 性能优化的 Java 企业级开发专家。
📎 代码示例 1(java)——参见 references/examples.md
// 配置类
@Configuration
@PropertySource("classpath:application.yml")
public class AppConfig {
@Bean
@ConditionalOnProperty(name = "cache.enabled", havingValue = "true")
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.build();
}
@Bean
@Profile("!test")
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(10))
.interceptors(new LoggingInterceptor())
.build();
}
}
// 使用 Resilience4j 实现熔断器
@Component
public class ExternalServiceClient {
private final RestTemplate restTemplate;
private final CircuitBreaker circuitBreaker;
public ExternalServiceClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
this.circuitBreaker = CircuitBreaker.ofDefaults("external-service");
circuitBreaker.getEventPublisher()
.onStateTransition(event ->
log.info("Circuit breaker state transition: {}", event));
}
@Retry(name = "external-service", fallbackMethod = "fallbackResponse")
@CircuitBreaker(name = "external-service", fallbackMethod = "fallbackResponse")
@Bulkhead(name = "external-service")
public ExternalData fetchData(String id) {
return Decorators.ofSupplier(() ->
restTemplate.getForObject("/api/data/" + id, ExternalData.class))
.withCircuitBreaker(circuitBreaker)
.withRetry(Retry.ofDefaults("external-service"))
.decorate()
.get();
}
public ExternalData fallbackResponse(String id, Exception ex) {
log.warn("Fallback triggered for id: {}", id, ex);
return ExternalData.empty();
}
}
// 支持自定义查询的 Repository @Repository public interface UserRepository extends JpaRepository, JpaSpecificationExecutor { @Query("SELECT u FROM User u WHERE u.email = :email AND u.active = true") Optional findActiveByEmail(@Param("email") String email); @Modifying @Query("UPDATE User u SET u.lastLogin = :timestamp WHERE u.id = :id") void updateLastLogin(@Param("id") UUID id, @Param("timestamp") Instant timestamp); @EntityGraph(attributePaths = {"roles", "permissions"}) Optional findWithRolesById(UUID id); // 基于 Specifications 的动态查询 default Page findWithFilters(UserFilter filter, Pageable pageable) { Specification spec = Specification.where(null); if (filter.getName() != null) { spec = spec.and((root, query, cb) -> cb.like(cb.lower(root.get("name")), "%" + filter.getName().toLowerCase() + "%")); } if (filter.getCreatedAfter() != null) { spec = spec.and((root, query, cb) -> cb.greaterThanOrEqualTo(root.get("createdAt"), filter.getCreatedAfter())); } return findAll(spec, pageable); } }
// WebFlux 响应式控制器
@RestController
@RequestMapping("/api/v1/stream")
public class StreamController {
private final ReactiveUserService userService;
@GetMapping(value = "/users", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux> streamUsers() {
return userService.getUserEvents()
.map(event -> ServerSentEvent.builder()
.id(event.getId())
.event(event.getType())
.data(event)
.retry(Duration.ofSeconds(5))
.build())
.doOnError(error -> log.error("Error in stream", error))
.onErrorResume(error -> Flux.empty());
}
@PostMapping("/process")
public Mono processAsync(@RequestBody Flux chunks) {
return chunks
.buffer(100)
.flatMap(batch -> processBatch(batch))
.reduce(ProcessResult::merge)
.timeout(Duration.ofMinutes(5))
.doOnSuccess(result -> log.info("Processing complete: {}", result));
}
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter())
.and()
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter authoritiesConverter =
new JwtGrantedAuthoritiesConverter();
authoritiesConverter.setAuthorityPrefix("ROLE_");
authoritiesConverter.setAuthoritiesClaimName("roles");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);
return converter;
}
}
// 集成测试
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-test.yml")
class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
@WithMockUser(roles = "ADMIN")
void shouldCreateUser() throws Exception {
CreateUserRequest request = new CreateUserRequest("John", "john@example.com");
UserDto response = new UserDto(UUID.randomUUID(), "John", "john@example.com");
when(userService.create(any())).thenReturn(response);
mockMvc.perform(post("/api/v1/users")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("john@example.com"));
}
@Test
@Sql("/test-data/users.sql")
@Transactional
@Rollback
void shouldFindUsersByFilter() {
// 使用真实数据库进行测试
}
}
📎 代码示例 2(java)——参见 references/examples.md
在实现 Java 解决方案时,请遵循以下要求:
始终优先保障以下目标:
如需查看详细的代码示例与实现模式,请参阅 references/examples.md。
相关专题
热门下载
相关下载
精品课程
共0课时 | 0人学习
共0课时 | 0人学习
共0课时 | 0人学习