柚子快報(bào)邀請碼778899分享:Eureka 注冊中心的使用
柚子快報(bào)邀請碼778899分享:Eureka 注冊中心的使用
環(huán)境 springboot + springcloud
Eureka-Server注冊中心服務(wù)端
pom.xml導(dǎo)入依賴
aplication.yml配置
server:
port: 10086
spring:
application:
name: eurekaserver # 服務(wù)名,需要配置
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
EurekaServerApplication.java啟動(dòng)類配置
@SpringBootApplication
@EnableEurekaServer // 開啟eureka的注冊中心功能
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
?
?
Service提供者
pom.xml
application.yml
spring:
application:
name: userservice
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
?
?
consumer消費(fèi)者 (消費(fèi)者也可以作為提供者身份出現(xiàn))
pom.xml
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 # 負(fù)責(zé)均衡 和 做拉取服務(wù)
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負(fù)載均衡 (service配置)
方式1:重寫IRule接口的實(shí)現(xiàn)Bean
@Bean
public IRule randomRule() {
return new RandomRule();
}
方式2:配置文件指定
application.xml
userservice: # 給某個(gè)微服務(wù)配置負(fù)載均衡規(guī)則,這里是userservice服務(wù)
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 負(fù)載均衡規(guī)則
# 當(dāng)?shù)谝淮卧L問時(shí)才會(huì)拉取服務(wù)再做緩存
饑餓加載配置:容器加載完畢后就拉取服務(wù)做緩存
ribbon:
eager-load:
enabled: true
clients:
- userservice # 指定一啟動(dòng)就加載的服務(wù),可以配置多個(gè)
- xxxservice1
柚子快報(bào)邀請碼778899分享:Eureka 注冊中心的使用
精彩鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。