Continue learning about SpringCloud today.
Last time we talked about the concept of microservices
This article is about how to register services on Eureka and how consumers spend their money in detail
The following code uses the simplest code examples, not real business code
The learning materials used in the study are as follows:
Article: SpringCloud minimalism Primer
Video: Spring Cloud from the beginning to the real world
Eureka is divided into two parts
- Eureka Server, registry
- Eureka Client. All microservices to be registered are connected to The Eureka Server through the Eureka Client to complete registration.
Eureka Server code implementation
- Create the parent project, POM.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7. RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Copy the code
- Create Module, POM.xml under the parent project
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.0.2. RELEASE</version>
</dependency>
</dependencies>
Copy the code
- Create the configuration file application.yml and add the configuration of Eureka Server.
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka/
Copy the code
Attributes that
Server. port: indicates the current Eureka Server service port.
Register-with-eureka: specifies whether to register the current Eureka Server service as a client.
Eureka. Client. fetch-fegistry: Specifies whether to obtain data from other Eureka Server services.
Eureka.client.service-url. defaultZone: access address of the registry.
- Creating a startup class
package com.janeroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class,args); }}Copy the code
Notes:
@springBootApplication: Declare this class to be an entry point to the SpringBoot service.
EnableEurekaServer: Declare that this class is a EurekaServer microservice that provides service registration and service discovery functions, i.e. registries.
Open a browser and visit http://localhost:8761. The following page is displayed. The registry is successfully started
Service provider code implementation
All microservices in the distributed system architecture need to be registered in the registry before they can be discovered and used. Service providers and service consumers are divided from the perspective of business. In fact, both service providers and service consumers complete registration by connecting Eureka Client to Eureka Server. Now realize a service provider and complete registration in Eureka Server. The general idea is to build a microservice application through Spring Boot and then register it with Eureka Server through Eureka Client. The process of creating a Eureka Client is very similar to that of creating a Eureka Server.
- Create Module, pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2. RELEASE</version>
</dependency>
</dependencies>
Copy the code
- Create the configuration file application.yml and add the configuration of Eureka Client
server:
port: 8010
spring:
application:
name: provider
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
Copy the code
Attribute Description:
Spring.application. name: the name of the current service registered with Eureka Server.
Eureka.client.service-url. defaultZone: access address of the registry.
Eureka. Instance. prefer-ip-address: indicates whether to register the IP address of the current service with the Eureka Server.
- Creating a startup class
package com.janeroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) { SpringApplication.run(ProviderApplication.class,args); }}Copy the code
- Entity class
package com.janeroad.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private long id;
private String name;
private int age;
}
Copy the code
- Repository
package com.janeroad.repository;
import com.janeroad.entity.Student;
import java.util.Collection;
public interface StudentRepository {
public Collection findAll(a);
public Student findById(long id);
public void saveOrUpdate(Student student);
public void deleteById(long id);
}
Copy the code
- RepositoryImpl
package com.janeroad.repository.impl;
import com.janeroad.entity.Student;
import com.janeroad.repository.StudentRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class StudentRepositoryImpl implements StudentRepository {
private static Map studentMap;
static {
studentMap = new HashMap<>();
studentMap.put(1L.new Student(1L."Zhang".22));
studentMap.put(2L.new Student(2L."Bill".23));
studentMap.put(3L.new Student(3L."Fifty".24));
}
@Override
public Collection findAll(a) {
return studentMap.values();
}
@Override
public Student findById(long id) {
return studentMap.get(id);
}
@Override
public void saveOrUpdate(Student student) {
studentMap.put(student.getId(),student);
}
@Override
public void deleteById(long id) { studentMap.remove(id); }}Copy the code
- Handler
package com.janeroad.controller;
import com.janeroad.entity.Student;
import com.janeroad.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
@RestController
@RequestMapping("/student")
public class StudentHandler {
@Autowired
private StudentRepository studentRepository;
@Value("${server.port}")
private String port;
@GetMapping("/findAll")
public Collection findAll(a){
return studentRepository.findAll();
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id){
return studentRepository.findById(id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
studentRepository.saveOrUpdate(student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id){
studentRepository.deleteById(id);
}
@GetMapping("/index")
public String index(a){
return "Current port:"+this.port; }}Copy the code
Open the browser and visit http://localhost:8761. The following page is displayed.
Run eurekaclient to start the class
The use of RestTemplate
- What is the REST
REST is a more popular Internet software architecture model, through the unified specification to complete the data access and interaction of different terminals, REST is a phrase abbreviation, known as representative state transfer, translated into Chinese means resource performance layer state transformation.
features
1. URL parameter transfer is more concise, as shown below:
- Non-restful URL: http://….. /queryUserById? id=1
- RESTful URL: http://…. /queryUserById/1
2. Complete resource sharing between different terminals. RESTful provides a set of specifications.
The middle HTTP request types (GET, POST, PUT, and DELETE) represent general operations, namely, CRUD:
- Obtaining Obtaining resources
- POST create create resources
- Put modify properties
- DELETE Deletes resources
What is the RestTemplate
RestTemplate is a REST-based service component provided by the Spring framework. It encapsulates HTTP requests and responses and provides many methods to access remote REST services, simplifying code development.
- How do I use RestTemplate?
Create Maven project, POM.xml.
2. Create the entity class
package com.janeroad.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private long id;
private String name;
private int age;
}
Copy the code
3, the Handler
package com.janeroad.controller;
import com.janeroad.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
@RestController
@RequestMapping("/rest")
public class RestHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection<Student> findAll(a){
return restTemplate.getForEntity("http://localhost:8010/student/findAll",Collection.class).getBody();
}
@GetMapping("/findAll2")
public Collection<Student> findAll2(a){
return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id){
return restTemplate.getForEntity("http://localhost:8010/student/findById/{id}",Student.class,id).getBody();
}
@GetMapping("/findById2/{id}")
public Student findById2(@PathVariable("id") long id){
return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
restTemplate.postForEntity("http://localhost:8010/student/save",student,null).getBody();
}
@PostMapping("/save2")
public void save2(@RequestBody Student student){
restTemplate.postForObject("http://localhost:8010/student/save",student,null);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
restTemplate.put("http://localhost:8010/student/update",student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id){
restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id); }}Copy the code
4. Start classes
package com.janeroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class,args);
}
@Bean
public RestTemplate restTemplate(a){
return newRestTemplate(); }}Copy the code
The RestTemplate is either a microservice or a pure Spring Boot application, but can invoke methods from the Eurekaclient service provider
RestTemplate Starts the effect
Service consumer code implementation
To realize a consumer of a user and call the relevant interface of the provider, the idea is to first build a microservice application through Spring Boot, and then register it with Eureka Server through Eureka Client. At this point, there is no difference between the provider and the consumer from the point of view of code. They are both Eureka clients. We artificially distinguish them from the business point of view, with the provider providing services and the consumer invoking services. The relevant interface of the service provider provider is invoked through the RestTemplate in the service Consumer.
- Create the Maven project, POM.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.0.2. RELEASE</version>
</dependency>
</dependencies>
Copy the code
- Create the configuration file application.yml
server:
port: 8020
spring:
application:
name: consumer
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
Copy the code
- Creating a startup class
package com.janeroad;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
@Bean
public RestTemplate restTemplate(a){
return newRestTemplate(); }}Copy the code
- Handler
package com.janeroad.controller;
import com.janeroad.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Collection;
@RestController
@RequestMapping("/consumer")
public class ConsumerHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findAll")
public Collection findAll(a){
return restTemplate.getForEntity("http://localhost:8010/student/findAll",Collection.class).getBody();
}
@GetMapping("/findAll2")
public Collection findAll2(a){
return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
}
@GetMapping("/findById/{id}")
public Student findById(@PathVariable("id") long id){
return restTemplate.getForEntity("http://localhost:8010/student/findById/{id}",Student.class,id).getBody();
}
@GetMapping("/findById2/{id}")
public Student findById2(@PathVariable("id") long id){
return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
restTemplate.postForEntity("http://localhost:8010/student/save",student,null).getBody();
}
@PostMapping("/save2")
public void save2(@RequestBody Student student){
restTemplate.postForObject("http://localhost:8010/student/save",student,null);
}
@PutMapping("/update")
public void update(@RequestBody Student student){
restTemplate.put("http://localhost:8010/student/update",student);
}
@DeleteMapping("/deleteById/{id}")
public void deleteById(@PathVariable("id") long id){
restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id); }}Copy the code
A consumer is actually a service consumer, indirectly accessing data
Consumer startup Effect
Other functions to add, delete, modify and check are omitted here. You can use Postman to test them