What is Eureka and Ribbon
Cluster setup
- Single machine simulation cluster
Steps to train of thought
- Create parent project import dependencies
- Create three databases with the same structure
- Create an Entity Class (POJO) Project (API)
- Create three service providers for the same business processing
- Create a service consumer
- Create three registries
- Created as maven project
- Modifying the hosts file
Create SpringCloud query points
- Why not just create a SpringBoot project?
A: There is a Maven dependency called Spring-Cloud-Dependencies that versions the components that Spring Cloud needs. Because of the strict version mapping of Spring Cloud components, an error can be reported if one is not noticed. It would be very troublesome if all the dependencies of the corresponding version were manually derived.
- In order to
spring cloud-Hoxton.SR10
thespring-cloud-dependencies
For example, versions of common components have been specified,
- Why does the parent POM use dependencyManagement?
A: In the POM file at the top level of our project, we will see the dependencyManagement element. The version of the JAR package is managed through its element, allowing a dependency to be referenced in a subproject without having to list the version number displayed. Maven moves up the parent-child hierarchy until it finds a project that has a dependencyManagement element, and then it uses the version number specified in that dependencyManagement element.
- DependencyManagement: Dependencies?
Create parent project import dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SpringCloud-Project</artifactId>
<version>1.0 the SNAPSHOT</version>
<properties>
<junit.version>4.13.2</junit.version>
<lombok.version>1.18.18</lombok.version>
<log4j.version>1.2.17</log4j.version>
<logback.version>1.2.3</logback.version>
<mybatis-starter.version>2.1.4</mybatis-starter.version>
<mysql.version>8.0.22</mysql.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<packaging>pom</packaging>
<! -- Project dependencies must be consistent -->
<dependencyManagement>
<dependencies>
<! -- Cloud dependency -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR10</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<! -- Boot dependency is compatible with cloud version -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.9. RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<! -- druid data source -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<! -- boot boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.9. RELEASE</version>
</dependency>
<! -- Logs are related to laziness -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<! -- mybaties -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-starter.version}</version>
</dependency>
<! -- Web dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.9. RELEASE</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
Copy the code
Three databases
Entity class
@Data
@NoArgsConstructor
@Accessors(chain = true)/ / chain
public class Dept implements Serializable {// Serialize
private Integer deptId;
private String dname;
private String db_source;
public Dept(String dname) {
this.dname = dname; }}Copy the code
Creating a service provider
- Import maven dependencies, and import your own entity class dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringCloud-Project</artifactId>
<groupId>org.example</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringCloud-Provider-8001</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<! -- Write your own entity class -->
<dependency>
<groupId>org.example</groupId>
<artifactId>SpringCloud-Api</artifactId>
<version>1.0 the SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<! --test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! --jetty-->
<! -- <dependency>-->
<! -- <groupId>org.springframework.boot</groupId>-->
<! -- <artifactId>spring-boot-starter-jetty</artifactId>-->
<! -- </dependency>-->
<! -- Hot Deployment Tool -->
<! -- <dependency>-->
<! -- <groupId>org.springframework.boot</groupId>-->
<! -- <artifactId>spring-boot-devtools</artifactId>-->
<! - < version > 2.3.9. RELEASE < / version > -- >
<! -- </dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<! -- Config service info -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
Copy the code
- Creating an interface Mapper interface
@Mapper
@Repository// Spring DAO layer markup
public interface DeptDao {
boolean addDept(Dept dept);
Dept getById(int id);
List<Dept> getAll(a);
}
Copy the code
- Create a Service layer interface
public interface DeptService {
boolean addDept(Dept dept);
Dept getById(int id);
List<Dept> getAll(a);
}
Copy the code
- Implementing the Service Interface
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
DeptDao deptDao;
@Override
public boolean addDept(Dept dept) {
return deptDao.addDept(dept);
}
@Override
public Dept getById(int id) {
return deptDao.getById(id);
}
@Override
public List<Dept> getAll(a) {
returndeptDao.getAll(); }}Copy the code
- Mybatis -config Enables level 2 cache
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="ture"/>
</settings>
</configuration>
Copy the code
- Configuration DeptMapper. XML
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cloud.dao.DeptDao">
<insert id="addDept">
insert into springcloud.dept (dname, db_source) values (#{dname},DATABASE())
</insert>
<select id="getById" resultType="com.cloud.pojo.Dept" parameterType="int">
select * from springcloud.dept where deptId=#{deptID}
</select>
<select id="getAll" resultType="com.cloud.pojo.Dept">
select * from springcloud.dept
</select>
</mapper>
Copy the code
- Configure application.yaml to use the Druid data source
server:
port: 8001
mybatis:
type-aliases-package: com.cloud.pojo
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
application:
name: springcloud-provider-dept
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springcloud? useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
# c
#SpringBoot does not inject these by default, you need to bind them yourself
#druid Data source proprietary configuration
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# Configure filters to monitor statistics interception, stat: monitor statistics, log4j: logging, wall: defend against SQL injection
# if an error is allowed, Java. Lang. ClassNotFoundException: org.. Apache Log4j. Properity
Import log4j dependencies
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=500
Where is the Eureka service registered
eureka:
client:
service-url: # registered address ~
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
instance:
instance-id: springcloud-provider-dept-8001
Configure the service information to specify what the service does
info:
app.name: The name of it
company.name: XXX company
Copy the code
- Druid description of parameter configuration
- Create a Controller
// Provides restful services
@RestController
public class DeptController {
@Autowired
private DeptService service;
@RequestMapping(value = "/add")// Use port 8001 instead of post. The consumer server is OK
public boolean add(@RequestBody Dept dept){
System.out.println(dept.getDname());
return service.addDept(dept);
}
@GetMapping("/byId/{id}")
public Dept getDeptById(@PathVariable int id){
return service.getById(id);
}
@GetMapping("/getAll")
public List<Dept> getAll(a){
returnservice.getAll(); }}Copy the code
- Creating a startup class
@EnableEurekaClient// Let Eureka find it
@SpringBootApplication
public class DeptProvider_8001{
public static void main(String[] args) { SpringApplication.run(DeptProvider_8001.class,args); }}Copy the code
- Change the port number in the configuration file, change the database name, and change the name of the startup class to the corresponding port number
Creating a registry
- Import dependence
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringCloud-Project</artifactId>
<groupId>org.example</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringCloud-Eurika-7001</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
Copy the code
- Create the launcher
@SpringBootApplication
@EnableEurekaServer// Activate Eureka Server configuration comments
public class Eureka_7001 {
public static void main(String[] args) { SpringApplication.run(Eureka_7001.class,args); }}Copy the code
- application.yaml
#server:
# port: 7001
# # Eureka configuration
#eureka:
# instance:
Eureka server instance name
# client:
# register-with-eureka: false # Indicates whether to register yourself with the Eureka registry
# fetch-registry: false # fetch-registry: false # fetch-registry: false
# service-url: # monitor page ~
# defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
application:
name: eureka-server-7001
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com
client:
# Whether it should register its information with the Eureka server for others to find. Set to false because it is the Eureka server
register-with-eureka: false
Whether eureka registry information should be obtained from the Eureka server. Set to false because it is the Eureka server
fetch-registry: false
service-url: # registered address ~
defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
Copy the code
- The other two are the same, just change the port number
Creating service consumers
- Import dependence
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringCloud-Project</artifactId>
<groupId>org.example</groupId>
<version>1.0 the SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringCloud-Consumer-dept-80</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<! -- Entity class -->
<dependency>
<groupId>org.example</groupId>
<artifactId>SpringCloud-Api</artifactId>
<version>1.0 the SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
</dependencies>
</project>
Copy the code
- Write the Configuration class
@Configuration
public class ConfigBeans {
//IRule, the interface that defines the "rule" of LoadBalancer. You can think of rules as load balancing policies. Well-known load balancing strategies include polling, response time based, etc
// The default is polling
@Bean
@LoadBalanced// Configure load balancing to implement RestTemplate
public RestTemplate restTemplate(a){
return newRestTemplate(); }}Copy the code
- Configuration class for load balancing (custom policy, or built-in policy (polling, random, weight…) ,), do not be in the same directory as the startup class, because in the same context, all service consumption will use the same load balancing policy.
@Configuration
public class MyRuleConfiguration {
@Bean
public IRule myRule(a){
return newRandomRule(); }}Copy the code
- Controller
@RestController
public class DeptConsumerController {
// Consumer, there should be no service layer
//RestTemplate is a simple restful service template that provides multiple convenient methods for accessing remote HTTP services
@Autowired
private RestTemplate restTemplate;
//private static final String REST_URL_PREFIX="http://localhost:8001";
private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT";// Access by service name
@GetMapping("/consumer/add/")
public boolean add(Dept dept){
System.out.println(dept.getDname());
return restTemplate.postForObject(REST_URL_PREFIX+"/add",dept,Boolean.class);
}
@GetMapping("/consumer/byId/{id}")
public Dept getDeptById(@PathVariable int id){
return restTemplate.getForObject(REST_URL_PREFIX+"/byId/"+id,Dept.class);
}
@GetMapping("/consumer/getAll")
public List getAll(a){
return restTemplate.getForObject(REST_URL_PREFIX+"/getAll",List.class); }}Copy the code
- application.yaml
server:
port: 80
# eureka configuration
eureka:
client:
register-with-eureka: false # Do not register yourself with Eureka
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/,http://eureka7002.com:7002/eureka/
Copy the code
- Start the class
@SpringBootApplication
//(" Service name ", "Custom Load Balancing Policy Configuration class.class")
@RibbonClient(name="SPRINGCLOUD-PROVIDER-DEPT",configuration= MyRuleConfiguration.class)
public class DeptConsumer_80 {
public static void main(String[] args) { SpringApplication.run(DeptConsumer_80.class,args); }}Copy the code
Modify the hosts file on the computer
- Three domain names represent. Three servers. Simulate it
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com
Copy the code
summary
The project structure
The dependence is going to be derivative of theta
The configuration file
- Key configurations for service providers
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
- Key configuration of the registry
- Key configurations for service consumers
Key annotations and objects
consumers
-
@LoadBalanced
.Load balancing the request template
-
@RibbonClient
.Use the Ribbon for load balancing
-
RestTemplate
In the Controller, make a request to the service provider
-
IRule
.Load balancing policy interface
-
- RestTemplate
= = = = = = = = = = = = = = = = = = = = = = = = = = = =
The registry
-
@EnableEurekaServer
.Enable comments for Eureka Server-related configurationsOn the startup class
Service provider
-
@EnableEurekaClient
.Enable the Eureka discovery configurationOn the startup class