记一些比较杂的关于SpringBoot等的小知识。
1.@SpringBootApplication由七个annotation,其中主要的三个annotation组成
- @SpringBootConfiguration:其本质是一个@Configuration注解,用于标记这个类是一个配置类,配置类就像以前的配置文件,不过我们可以通过简单的方法向Ioc容器添加组件(例:@Bean)
- @EnableAutoConfiguration:主要的是将导入的Spring的jar包中的MAT-INF/spring.factories中的xxxAutoConfiguration加载到容器中,主要添加了Spring本身需要的一些组件,SpringFactoriesLoader对这些组件进行加载。
- ComponentScan:加载我们在子目录下通过注解形式创建的组件(例如:@Service,@controller等),因此,我们一般将xxxApplication这个类,放在根目录下,其他组件放在子目录下。
2.RestTemplate可以通过这个方法获取URL的资源,需要两边的值一样。例如:
两个服务(Order需要查询Item,Item是商品的数据,Order是订单数据)
@RestController
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("item/{itemId}")
//注意这里需要返回Item这个对象
public Item itemController(@PathVariable("itemId") Long l) throws JsonProcessingException {
return this.itemService.getItemById(l);
}
}
对应的,如果我们在另外一端需要获取这个资源,我们需要如下这么写。
@Service
public class OrderService {
@Autowired
@LoadBalanced
private RestTemplate restTemplate;
public Order getOrderById(Long l){
System.err.println("调用这个方法");
//注意这里参数是Item.class,URL是因为我注册了eureka微服务
Item result = this.restTemplate.getForObject("http://app-item/item/2",Item.class);
System.err.println(result);
return new Order();
}
}
3.FeignClient的使用流程
(1)添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
(2)创建接口
@FeignClient(value = "app-item")
public interface ItemFeignClient {
@GetMapping(value = "/item/{id}")
Item queryItemById(@PathVariable(value = "id")Long id);
}
(3)在@SpringBootApplication添加注解
@EnableFeignClients(basePackages = "com.liu.eurekaorder.Feign")
这样我们可以在service中不使用RestTemplate就能查询到结果了
@Autowired
private ItemFeignClient itemFeignClient;
//service层的核心代码
public Order getOrderById(Long l){
System.err.println("调用这个方法");
//注意这里参数是Item.class,URL是因为我注册了eureka微服务
Item result = itemFeignClient.queryItemById(l);
System.err.println(result);
return new Order(2L,"liumou",result);
}
流程分析:
1、由于我们在入口程序使用了@EnableFeignClients注解,Spring启动后会扫描标注了@FeignClient注解的接口,然后生成代理类。
2、我们在@FeignClient接口中指定了value,其实就是指定了在Eureka中的服务名称。
3、在FeignClient中的定义方法以及使用了SpringMVC的注解,Feign就会根据注解中的内容生成对应的URL,然后基于Ribbon的负载均衡去调用REST服务。
例如上面的例子会形成的URL为:http://app-item/item/id;这里的id为方法的参数值。