作为消费者访问提供者提供的功能(eureka的铺垫案例)

1. 实体类、提供者的创建如本随笔者的Euraka适合初学者的简单小demo中有所展示

2. 创建子工程作为消费者

(1) 添加依赖:切记引入实体类的依赖

<dependencies>
        <dependency>
            <groupId>com.offcn</groupId>
            <artifactId>microservice_cloud_02_api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

 (2) application.yml文件中设置端口号为80

  (3) 创建配置类

@Configuration
public class ConfigBean {

    @Bean
    public RestTemplate getConfigBean(){
        return new RestTemplate();
    }
}

 (4) 创建controller类,实现消费者访问提供者功能的功能

@RestController
public class ProductController_Customer {

    @Autowired
    private RestTemplate restTemplate;

    private static final String REST_URL_PREFIX = "http://localhost:8001";

    @RequestMapping(value = "/customer/product/add")
    public boolean add(Product product){
        return restTemplate.postForObject(REST_URL_PREFIX+"/product/add",product,Boolean.class);
    }

    @RequestMapping(value = "/customer/product/get/{id}")
    public Product get(@PathVariable("id") Long id){
        return restTemplate.getForObject(URI.create(REST_URL_PREFIX+"/product/get/"+id),Product.class);
    }

    @RequestMapping(value = "/customer/product/get/list")
    public List<Product> list(){
        return restTemplate.getForObject(URI.create(REST_URL_PREFIX+"/product/get/list"),List.class);
    }
}

 (5) 创建启动类

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class CustomerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CustomerApplication.class,args);
    }
}

 因为这个实现在功能对且复杂的情况下,而且男用户量多的时候会配置很多的配置类,太过繁琐,以至于用了eureka来替代了它

猜你喜欢

转载自www.cnblogs.com/xiaoyuer0506/p/11817425.html