Spring章节复习已经过去,新的章节SpringCloud开始了,这个章节中将会回顾微服务相关
主要依照以下几个原则
相关的代码已经上传到
链接: SpringCloudServiceDemo
可以进入master分支去看
需求分析
一般通过RestTemplate,这种就是通过RestFul风格调用url的方式进行微服务信息的传递
@Component
public class BeanFactory {
@Bean
public static RestTemplate getRestTemplate(){
return new RestTemplate();
}
@Bean("curTemplate")
public RestTemplate RestTemplate(){
return new RestTemplate();
}
}
配置Bean,可以用过静态方法或者直接注入的方式拿到;
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
配置SpringBootApplication就是为
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
public Order queryOrderById(Long orderId) {
// 通过静态工厂去拿
Order order = orderMapper.findById(orderId);
String url = "http://localhost:8081/user/" + order.getUserId();;
order.setUser(BeanFactory.getRestTemplate().getForObject(url, User.class));
return order;
}
}
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
@Qualifier("curTemplate")
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 通过原生AutoWired去拿
Order order = orderMapper.findById(orderId);
String url = "http://localhost:8081/user/" + order.getUserId();
order.setUser(restTemplate.getForObject(url, User.class));
return order;
}
}

进行debug,加载源码包

配置断点

调用我们后端传入的url


创建一个工厂,存放url

工厂创建后,对request请求路径封装

这里的方法就是将请求转发过去,获取一个响应
