環(huán)境 springboot + springcloud
Eureka-Server注冊中心服務端
pom.xml
導入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.2.7.RELEASE</version> <!-- 一般在父工程中就配置了 -->
</dependency>
aplication.yml
配置
server:
port: 10086
spring:
application:
name: eurekaserver # 服務名,需要配置
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
EurekaServerApplication.java
啟動類配置
@SpringBootApplication
@EnableEurekaServer // 開啟eureka的注冊中心功能
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
?
?
Service提供者
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.7.RELEASE</version> <!-- 一般在父工程中就配置了 -->
</dependency>
application.yml
spring:
application:
name: userservice
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
?
?
consumer消費者 (消費者也可以作為提供者身份出現(xiàn))
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.7.RELEASE</version> <!-- 一般在父工程中就配置了 -->
</dependency>
application.yml
spring:
application:
name: orderservice
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
OrderApplication
配置RestTemplate的Bean加入到Spring容器中
@MapperScan("cn.xxx.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
@LoadBalanced # 負責均衡 和 做拉取服務
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
OrderService
利用RestTemplate調(diào)用 UserService接口
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
Order order = orderMapper.findById(orderId);
// restTemplate.getForObject(請求地址, 返回值類型);
String url = "http://userservice/user/" + order.getUserId(); // userservice是提供者的spring.application.name
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}
}
Ribbon負載均衡 (service配置)
方式1:重寫IRule接口的實現(xiàn)Bean
@Bean
public IRule randomRule() {
return new RandomRule();
}
方式2:配置文件指定
application.xml
文章來源:http://www.zghlxwxcb.cn/news/detail-693589.html
userservice: # 給某個微服務配置負載均衡規(guī)則,這里是userservice服務
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 負載均衡規(guī)則
# 當?shù)谝淮卧L問時才會拉取服務再做緩存
饑餓加載配置
:容器加載完畢后就拉取服務做緩存文章來源地址http://www.zghlxwxcb.cn/news/detail-693589.html
ribbon:
eager-load:
enabled: true
clients:
- userservice # 指定一啟動就加載的服務,可以配置多個
- xxxservice1
到了這里,關于Eureka 注冊中心的使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!