我正在尝试使mockMvc 调用与wiremock 一起运行。但是代码中下面的mockMvc调用不断抛出404而不是预期的200 HTTP状态代码。
我知道wiremock正在运行..当wiremock运行时我可以通过浏览器执行http://localhost:8070/lala 。
有人可以建议吗?
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApp.class)
@AutoConfigureMockMvc
public class MyControllerTest {
@Inject
public MockMvc mockMvc;
@ClassRule
public static final WireMockClassRule wireMockRule = new WireMockClassRule(8070);
@Rule
public WireMockClassRule instanceRule = wireMockRule;
public ResponseDefinitionBuilder responseBuilder(HttpStatus httpStatus) {
return aResponse()
.withStatus(httpStatus.value());
}
@Test
public void testOne() throws Exception {
stubFor(WireMock
.request(HttpMethod.GET.name(), urlPathMatching("/lala"))
.willReturn(responseBuilder(HttpStatus.OK)));
Thread.sleep(1000000);
mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/lala")) .andExpect(status().isOk());
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个即时日期,例如:2020-03-09T20:13:57.089Z并且我想在即时中找到第二天的结束时间,例如 - 2020-03-10T23:59:59.089Z(这将是与初始日期相比的第二天的结束时间)
如何使用 Java 中的 Instant 来做到这一点?
有一个耗时的操作(大约10分钟),但卡夫卡在5分钟后重新平衡,甚至我暂停了消费者.消费者方法:
@KafkaListener(topics = {TopicAppoint.EXECUTE_SCHOOL_DATA_STATICS_TASK})
public void receiveMessage(@Payload String payload, Consumer<String, String> consumer) {
Set<TopicPartition> assignment = consumer.assignment();
consumer.pause(assignment);
if (StringUtils.isNotEmpty(payload)) {
SchoolStatisticsTaskDTO staticsTaskDTO = JSONObject.parseObject(payload, SchoolStatisticsTaskDTO.class);
Optional<SchoolStatisticsTaskDO> taskOptional = schoolStatisticsTaskRepository.findById(staticsTaskDTO.getTrackId());
taskOptional.ifPresent(schoolStaticsTaskDO -> {
// handler
});
}
consumer.resume(assignment);
}
Run Code Online (Sandbox Code Playgroud)
这是我的配置:
kafka:
bootstrap-servers: 192.168.0.230:9092
producer:
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
retries: 3
properties:
max.request.size: 12582912
consumer:
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
group-id: dc-fitness-data-consumer-group
properties:
max.partition.fetch.bytes: 12582912
#enable-auto-commit: false
listener:
ack-mode: record
concurrency: 6
Run Code Online (Sandbox Code Playgroud)
日志
13:09:20.219 [org.springframework.kafka.KafkaListenerEndpointContainer#2-0-C-1] INFO o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-25, groupId=dc-fitness-data-consumer-group] Attempt …Run Code Online (Sandbox Code Playgroud) 我有一个具有 Id 属性的实体“任务”,但我不需要在 JSON 文件中返回该字段。
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private Integer Id;
@JsonProperty("task")
private String taskName;
private String status;
//getter and setter
}
Run Code Online (Sandbox Code Playgroud)
但是,当我发出 get 请求时,注释 @JsonIgnore 不会过滤该字段,如下所示:
{
"status": "started",
"timestamps": {
"submitted": "2018-12-31T00:34:20.718+0000",
"started": "2018-12-31T00:34:20.718+0000",
"completed": "2018-12-31T00:34:20.718+0000"
},
"id": 40001,
"task": "q094hiu3o"
}
Run Code Online (Sandbox Code Playgroud)
防止显示“Id”的正确方法是什么?
我有两个 Spring Boot 应用程序,它们通过 JMS 消息传递和 ActiveMQ 进行通信。
一个应用程序向另一个应用程序发送一个包含 LocalDateTime 属性的对象。此对象被序列化为 JSON,以便发送到其他应用程序。
我面临的问题是 Jackson 在尝试将传入的 json 映射到我的对象时无法反序列化 LocalDateTime 属性。LocalDateTime 属性在到达“侦听器应用程序”时具有以下格式:
"lastSeen":{
"nano":0,
"year":2019,
"monthValue":4,
"dayOfMonth":8,
"hour":15,
"minute":6,
"second":0,
"month":"APRIL",
"dayOfWeek":"MONDAY",
"dayOfYear":98,
"chronology":{
"id":"ISO",
"calendarType":"iso8601"
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的例外如下:
org.springframework.jms.support.converter.MessageConversionException: Failed to convert JSON message content; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of java.time.LocalDateTime
我能够通过使用以下注释暂时解决这个问题:
@JsonSerialize(as = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class, as = LocalDateTime.class)
private LocalDateTime lastSeen;
Run Code Online (Sandbox Code Playgroud)
但它们属于jackson 数据类型 jsr310,现在已弃用。
有什么方法/替代方法可以在不使用上述注释的情况下反序列化这个 LocalDateTime 属性?或者我如何使用推荐的jackson-modules-java8 让它工作?
使用java流,如何在同一类上通过2个键从列表创建索引索引?
我在这里给出一个代码示例,我希望地图“ personByName”通过firstName或lastName获取所有人,所以我想获取3个“ steves”:当它们是firstName或lastname时。我不知道如何混合使用2个Collectors.groupingBy。
public static class Person {
final String firstName;
final String lastName;
protected Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
@Test
public void testStream() {
List<Person> persons = Arrays.asList(
new Person("Bill", "Gates"),
new Person("Bill", "Steve"),
new Person("Steve", "Jobs"),
new Person("Steve", "Wozniac"));
Map<String, Set<Person>> personByFirstName = persons.stream().collect(Collectors.groupingBy(Person::getFirstName, Collectors.toSet()));
Map<String, Set<Person>> personByLastName = persons.stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()));
Map<String, Set<Person>> personByName …Run Code Online (Sandbox Code Playgroud) 我试图在两次范围内生成 10 个随机时间,并且有一个条件,即生成的时间之间不能少于 30 分钟。因此,如果我在上午 10:00 开始并在下午 05:00 结束,则它们之间的时间必须至少间隔 30 分钟。
我已经可以获得随机时间,但不知道如何将条件放在那里,有什么想法吗?
public LocalTime between(LocalTime startTime, LocalTime endTime) {
int startSeconds = startTime.toSecondOfDay();
int endSeconds = endTime.toSecondOfDay();
int randomTime = ThreadLocalRandom
.current()
.nextInt(startSeconds, endSeconds);
return LocalTime.ofSecondOfDay(randomTime);
}
Run Code Online (Sandbox Code Playgroud)
我把它放在一个 for 循环中以获得 10 个
不传递Executorto CompletableFuture.runAsync(),ForkJoinPool则使用公共。相反,对于我想要异步执行的简单任务(例如,我不需要链接不同的任务),我可能只使用ForkJoinPool.commonPool().execute().
为什么应该优先考虑另一个?例如,是否runAsync()有任何实质性的开销execute()?前者比后者有什么特别的优势吗?
java multithreading asynchronous forkjoinpool completable-future
我有一个带有 Aspectj 的 Spring 启动代码。这段代码是用基本的 MVC 架构编写的。然后我只是尝试用 MockMVC 测试它。但是当我尝试对其进行测试时,Aspectj 并没有中断。Aspectj 有没有特殊的配置?
控制器:
@GetMapping("user/{userId}/todo-list")
public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){
...handle it with service method.
}
Run Code Online (Sandbox Code Playgroud)
方面:
@Pointcut("execution(* *(.., @RequestUser (*), ..))")
void annotatedMethod()
{
}
@Before("annotatedMethod() && @annotation(requestUser)")
public void adviseAnnotatedMethods(JoinPoint joinPoint, RequestUser requestUser)
{
...
}
Run Code Online (Sandbox Code Playgroud)
测试:
@WebMvcTest(value = {Controller.class, Aspect.class})
@ActiveProfiles("test")
@ContextConfiguration(classes = {Controller.class, Aspect.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest
{
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private Controller controller;
@MockBean
private Service service;
@Before
public void …Run Code Online (Sandbox Code Playgroud) 我有UT,顺利通过
@Test
public void test() {
String text1 = "2009-07-10T14:30:01.001Z";
String text2 = "2009-07-10T14:30:01.001+03:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(text1, f);
ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(text2, f);
System.out.println(zonedDateTime1);
System.out.println(zonedDateTime2);
}
Run Code Online (Sandbox Code Playgroud)
输出是
2009-07-10T14:30:01.001Z
2009-07-10T14:30:01.001+03:00
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试在 spring-controller 上使用这种模式时
@GetMapping
public ResponseEntity get( @RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ")
ZonedDateTime start) {
Dto result = service.get(start);
return new ResponseEntity(result, getHeaders(), HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
例如,仅当我传递 Z 而不是时区时,它才有效
2009-07-10T14:30:01.001Z
Run Code Online (Sandbox Code Playgroud)
但是当尝试传递时区偏移时 - 出现错误消息
“无法将类型“java.lang.String”的值转换为所需类型“java.time.ZonedDateTime”;嵌套异常为 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换输入 [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.ZonedDateTime] 获取值 '2009-07-10T14:30:01.001 03:00';嵌套异常是 java.lang.IllegalArgumentException:解析尝试失败的值 [2009-07-10T14:30:01.001 03:00]”,
我尝试像这样通过邮递员传递请求
POST …Run Code Online (Sandbox Code Playgroud) java ×9
spring-boot ×4
java-8 ×3
jackson ×2
spring ×2
apache-kafka ×1
aspectj ×1
asynchronous ×1
controller ×1
date ×1
forkjoinpool ×1
hibernate ×1
java-stream ×1
java-time ×1
json ×1
localtime ×1
spring-jms ×1
spring-kafka ×1
time ×1
wiremock ×1