1. Create a Maven project, ArtificatId is microservice-sample-consumer-alarm
2. Add dependencies
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <!-- Introduce the dependency of spring cloud--> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Camden.SR4</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <!-- Add spring-boot maven plugin --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
3. Create an entity class
4. Create a startup class
@SpringBootApplication public class ConsumerAlarmApplication { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(ConsumerAlarmApplication.class, args); } }
The role of @ is to instantiate a bean and name it with the name of the method, which is equivalent to:
RestTemplate restTemplate = new RestTemplate()
5. Create a Controller and use RestTemplate to request production microservices
@RestController public class AlarmConsumerController { @Autowired private RestTemplate restTemplate; @GetMapping("/alarm/findAll") public User findById() { return this.restTemplate.getForObject("http://localhost:8000" , AlarmBean.class); } }
6. Write application.yml
server: port: 8010