Spring Cloud微服务实战学习记录(第二章)
本书所使用的为spring boot2.0之前的版本,所以很多地方实际操作的时候并不一样,本文将在学习调试中使用新版本2.0.6,对原文进行补正
第一个例子,“Hello World”
位于原书17页。没想到第一个例子就出现问题,按照书上的步骤,会出现404。经过查资料发现,是因为启动类所在package与controller所在的package同级,所以我手动将启动类放到上面一层package下,问题解决。
编写单元测试
位于原书18页。我发现自动生成的测试文件的@RunWith(SpringRunner.class)与书上的@RunWith(SpringJUnit4ClassRunner.class)不同,点进SpringRunner类一看只是继承了SpringJUnit4ClassRunner类,重写的方法也是用的super(),并没有什么改动。去查看官档:
SpringRunner is an alias for the SpringJUnit4ClassRunner.
原来只是别名。。搞这么多注解对新手太不友好了。。
之后只添加@SpringBootTest就可以启动项目了,代码如下
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloApplicationTests {
private MockMvc mvc;
@Before
public void setUp(){
System.out.println("B4");
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void hello() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Hello World")));
}
}
@SpringBootTest可以被当作@ContextConfiguration,书上提到的@SpringApplicationConfiguration已经不再适用于新版本了。@SpringBootTest不会启动server,使用它的webEnvironment属性可以根据需要重新定义运行环境。
Actuator及其端点
位于原书28页。此处的提到的各种端点,我试了几次并不能通过网页打开,查资料后发现,由于安全方面的考虑,已经被关闭了。可以通过在application.yml或者application.properties配置文件中打开,如下:
management:
endpoints:
web:
exposure:
include: ["beans","mappings"]
关于书中38页提到的/shutdown端点,现版本已经被移到endpoint属性下。配置如下:
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true
由于该端点使用的是POST方法,所以我们使用curl对其进行访问,命令和结果如下所示:
C:\Users\hand\Downloads\hello\hello>curl -X POST localhost:8080/actuator/shutdown
{"message":"Shutting down, bye..."}
Ps:application.java 文件不能直接放在main/java文件夹下,必须要建一个包把他放进去。不然就会报错误提示:“Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package”