springCloud 1. 통합 eureka 분포 식 서비스 발견 프레임 워 크
1. 유레카 소개
유레카 는 넷 플 릭 스 가 개발 한 서비스 발견 프레임 워 크 로 REST 기반 서비스 다.
유레카 서버 와 유레카 클 라 이언 트
주로:
[외부 체인 이미지 저장 에 실 패 했 습 니 다. 원본 사이트 에 도 난 방지 체인 메커니즘 이 있 을 수 있 습 니 다. 그림 을 저장 해서 직접 업로드 하 는 것 을 권장 합 니 다 (img - C0z9laYE - 157076979086) (BDB475AE408B4089B5B993F0A6FC85F 3)]
2. 유레카 서버 구축
2.1 설정 에 의존
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Greenwich.SR2version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
2.2 application. yml 프로필
server:
port: 7961
eureka:
instance:
hostname: localhosh #eureka
client:
fetch-registry: false
register-with-eureka: false
service-url:
defaultZone: http://localhost:${server.port}/eureka/
2.3 시작 클래스 코드
@SpringBootApplication
@EnableEurekaServer
public class SpringcloudMsEureka7961Application {
public static void main(String[] args) {
SpringApplication.run(SpringcloudMsEureka7961Application.class, args);
}
}
2.4 테스트
방문http://localhost:7961/
3. 서비스 제공 자 구축
3.1 의존 설정
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Greenwich.SR2version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
3.2 application. yml 설정 (아 리 Durid 와 데이터베이스 읽 기와 쓰기 분리)
server:
port: 6001
eureka:
client:
fetch-registry: false
register-with-eureka: true
service-url:
defaultZone: http://localhost:7961/eureka/
instance:
prefer-ip-address: true
logging:
level:
com.vip.weborder.mapper: debug
mybatis-plus:
mapper-locations: classpath:mappers/**/*.xml
spring:
datasource:
druid:
stat-view-servlet:
loginUsername: root
loginPassword: root
dynamic:
datasource:
master:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://120.24.94.104:3316/aaaa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
druid:
initial-size: 3
max-active: 8
min-idle: 2
max-wait: -1
min-evictable-idle-time-millis: 30000
max-evictable-idle-time-millis: 30000
time-between-eviction-runs-millis: 0
validation-query: select 1
validation-query-timeout: -1
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
max-open-prepared-statements: 100
filters: stat,wall
share-prepared-statements: true
slave_1:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://120.24.94.104:3317/aaaa?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
druid:
initial-size: 3
max-active: 8
min-idle: 2
max-wait: -1
min-evictable-idle-time-millis: 30000
max-evictable-idle-time-millis: 30000
time-between-eviction-runs-millis: 0
validation-query: select 1
validation-query-timeout: -1
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
max-open-prepared-statements: 100
filters: stat,wall
share-prepared-statements: true
<!-- -->
application:
name: ms-provider
3.3 시작 클래스 코드
@SpringBootApplication
@EnableEurekaClient // Eureka
public class ShopProviderApplication {
public static void main( String[] args){
SpringApplication.run(ShopProviderApplication.class, args);
}
}
4. 서비스 소비자 측 구축
4.1 도입 의존
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>com.qfgroupId>
<artifactId>spring-cloudartifactId>
<version>0.0.1-SNAPSHOTversion>
parent>
<groupId>com.examplegroupId>
<artifactId>springcloud-ms-consumer-8080artifactId>
<version>0.0.1-SNAPSHOTversion>
<name>springcloud-ms-consumer-8080name>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-ribbonartifactId>
dependency>
<dependency>
<groupId>com.qfgroupId>
<artifactId>spring-cloudartifactId>
<version>0.0.1-SNAPSHOTversion>
<exclusions>
<exclusion>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
exclusion>
<exclusion>
<groupId>tk.mybatisgroupId>
<artifactId>mapper-spring-boot-starterartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Greenwich.SR2version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
project>
4.2 application. yml 설정
spring:
application:
name: shop-consumer
server:
port: 8080
eureka:
client:
fetch-registry: true
register-with-eureka: false
service-url:
defaultZone: http://localhost:7961/eureka/
4.3 시작 클래스 코드
@SpringBootApplication
@EnableEurekaClient
public class SpringcloudMsConsumer8080Application {
public static void main(String[] args) {
SpringApplication.run(SpringcloudMsConsumer8080Application.class, args);
}
}
5 리본 부하 균형 시작 (단순 시작 기본 값)
5.1 설정 의존
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-ribbonartifactId>
dependency>
5.2 부하 균형 실현
Ribbon 은 클 라 이언 트 의 부하 균형 기 도구 일 뿐 실현 하기 가 매우 간단 합 니 다. 우 리 는 RestTemplate 를 주입 하 는 bean 에 @ LoadBalanced 를 추가 하면 됩 니 다.다음 과 같다.
@Configuration
public class BeanConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
5.3 시작 클래스 설정
@SpringBootApplication
@EnableEurekaClient
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
5.4 서비스의 호출
, + , 。
@RestController
@RequestMapping(value="/user")
public class UserController {
@Resource
private RestTemplate restTemplate;
@RequestMapping(value = "/ticket/{id}", method = RequestMethod.GET)
public Object getTicket(@PathVariable(value = "id") Integer id) {
Person person = new Person();
person.setId(23);
person.setName(" ");
// shop-provider , ip:
List ticketList = restTemplate.getForObject("http://shop-provier/ticket", List.class, person);
return ticketList;
}
}
5.5 부하 균형 전략
Ribbon IRule, , , Ribbon :
유명무실 하 다
묘사 하 다.
RoundRobbinRule
폴 링
RandomRule
무 작위 선택
RetryRule
폴 링 방식 에 따라 서 비 스 를 호출 합 니 다. 만약 에 그 중의 특정한 서 비 스 를 사용 할 수 없 지만 몇 번 을 시도 합 니 다. 만약 에 몇 번 을 시도 해 보 았 지만 성공 하지 못 하면 이 서 비 스 를 호출 하지 않 고 다른 사용 가능 한 서 비 스 를 문의 합 니 다.
AvailabilityFilteringRule
여러 번 접근 할 수 없고 한도 값 을 초과 하 는 서 비 스 를 걸 러 낸 다음 에 다른 서 비 스 를 호출 할 것 입 니 다.
WeightedResponseTimeRule
평균 응답 시간 에 따라 가중치 를 계산 하고 응답 이 빠 를 수록 가중치 가 커 질 수록 선택 되 기 쉽다.서비스 가 처음 재 개 되 었 을 때 가중치 가 폴 링 방식 에 따라 집계 되 지 않 았 다.통계 정보 가 충분 할 때 가중치 정보 에 따라 방문 할 것 이다.
ZoneAvoidanceRule
서버 가 있 는 지역 성능 과 가용성 선택 서버 를 판단 합 니 다.
BestAvailableRule
여러 번 접근 할 수 없 는 서 비 스 를 걸 러 내 고 병발 량 이 가장 적은 서 비 스 를 선택 하여 호출 합 니 다. 기본 방식 입 니 다.
Ribbon :
@Bean
public IRule getRule() {
return new RandomRule();
}
5.6 사용자 정의 부하 균형 정책
AbstractLoadBalancerRule , choose , , :
public class Customize_Rule extends AbstractLoadBalancerRule {
private static Logger logger = LoggerFactory.getLogger(Customize_Rule.class);
private int currentIndex = 0; //
private int num = 1; //
private int limit = 5;
/**
*
* @param iClientConfig
*/
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
@Override
public Server choose(Object key) {
ILoadBalancer balancer = getLoadBalancer();
return choose(balancer, key);
}
private Server choose(ILoadBalancer balancer, Object key) {
Server server = null;
while(null == server) {
//
List reachableServers = balancer.getReachableServers();
if (0 == reachableServers.size()) {
logger.error(" ");
return null; // while
}
int total = reachableServers.size(); //
synchronized (this) {
/**
* , , ,
*/
if (currentIndex + 1 > total) {
currentIndex = 0;
server = reachableServers.get(currentIndex); //
num = 0;
num++;
} else {
if(limit == num) {
currentIndex++;
num = 0;
if(currentIndex == total) {
currentIndex=0;
server = reachableServers.get(currentIndex); //
num++;
}else{
server = reachableServers.get(currentIndex);
num++;
}
}else {
server = reachableServers.get(currentIndex);
num++;
}
}
}
}
return server;
}
}
, :
@Bean
public IRule getRule() {
return new Customize_Rule();
}
이러한 Controller 층 에 대한 침입 이 너무 강하 고 보기 불편 하기 때문에 다음 Feign 으로 부하 균형 을 이 룰 수 있 습 니 다.
6. Feign 부하 균형
eign 은 Ribbon 의 또 다른 부하 균형 을 바탕 으로 하 는 클 라 이언 트 프레임 워 크 로 인터페이스 에서 호출 할 서비스 이름 만 정의 하면 되 고 사용 하기 가 매우 간단 합 니 다.
6.1 의존 도 추가
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
6.2 시작 클래스 설정
시작 클래스 에 @ EnableFeignClient 주 해 를 추가 하면 feign 을 시작 할 수 있 습 니 다. 다음 과 같 습 니 다.
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ShopConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ShopConsumerApplication.class, args);
}
}
6.3 service 층 은 직접 주석 으로 다른 모듈 을 호출 합 니 다.
@Service
@FeignClient(name = "shop-provier")
public interface TicketService {
@RequestMapping(value = "ticket", method = RequestMethod.GET)
public List<Ticket> getAllTicket(Person person);
}
이렇게 해서 우 리 는 Controller 층 에서 평소 쓰 던 것 과 똑 같이 사용 합 니 다. 다만 Service 층 이 다 르 기 때문에 더욱 편안 해 보 입 니 다.
6.4 yml 설정
시간 초과 문제 가 발생 할 수 있 으 니 설정 시간 을 설정 할 수 있 습 니 다.
client:
config:
default:
connectTimeout: 160000000
readTimeout: 160000000
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.