Use IDEA to build a SpringCloud project

Create Eurake Server

1. Right-click on the selected project -> New -> Module

Check Web->Spring Web

 勾选Spring Cloud Discovery->Eureka Server

2. Modify the application.properties file

server.port=8761
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

3. Modify the startup class DemocloudApplication

Add @EnableEurekaServer, which indicates that the annotation class is an Eureka Server.

@SpringBootApplication
@EnableEurekaServer
public class DemocloudApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemocloudApplication.class, args);
    }
}

4. Start the project

Enter http://localhost:8761/ in your browser

Create a producer

1、勾选Spring Cloud Discovery->Eureka Discovery Client

2. Modify the application.properties file

server.port=7901
spring.application.name=demo-user
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
logging.level.root=INFO

3. Modify the startup class DemoclientApplication

Add @EnableEurekaClient, which indicates that the annotation class is a producer.

@SpringBootApplication
@EnableEurekaClient
public class DemoclientApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoclientApplication.class, args);
    }
}

4. Create Controller

@RestController
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/sayHello")
    public String sayhello(){
        return "I`m provider 1 ,Hello consumer!";
    }
}

5. Running the service

Enter http://localhost:7901/user/sayHello in your browser

create consumer

1、勾选Spring Cloud Discovery->Eureka Discovery Client

2. Modify the application.properties file

server.port=7902
spring.application.name=demo-guest
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
logging.level.root=INFO

3. Modify the startup class DemoguestApplication

Add @EnableDiscoveryClient, which indicates that the annotation class is a consumer.

@SpringBootApplication
@EnableDiscoveryClient
public class DemoguestApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoguestApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

4. Create Controller

@RestController
public class GuestController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/hello")
    public String hello(){
        //服务地址 http://{服务提供者应用名名称}/{具体的controller}
        String url="http://DEMO-USER/user/sayHello";
        //返回值类型和我们的业务返回值一致
        return restTemplate.getForObject(url, String.class);
    }
}

5. Running the service

Enter http://localhost:7902/hello in your browser

Guess you like

Origin blog.csdn.net/watson2017/article/details/123376907