com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
${latest.version}
spring:
application:
name: {应用名称}
cloud:
nacos:
discovery:
server-addr: 111.52.99.114:18848
username: nacos
password: nacos
PS:nacos2.0除了需要8848的端口之外,还新增了端口+1000的新端口用于客户端和服务端GRPC通信的端口,所以如果是自己部署的nacos需要放开这俩个端口,服务才可以启动成功。
3.1 添加Spring Cloud原生注解 @EnableDiscoveryClient
3.2 客户端服务使用@LoadBalanced
做负载均衡调用
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
PS:使用
@LoadBalanced
需要引入负载均衡器的实现才能生效。
org.springframework.cloud spring-cloud-starter-loadbalancer
3.3 通过restTemplate
调用
@RequestMapping(value = "mappingURL", method = RequestMethod.GET)
public String echo(@PathVariable String str) {
return restTemplate.getForObject("http://{服务提供者-服务名}/echo/" + str, String.class);
}
服务注册成功,nacos控制台可以看到服务列表,服务调用正常。如图:
org.apache.dubbo
dubbo
2.7.15
org.apache.dubbo
dubbo-spring-boot-starter
2.7.15
com.alibaba.nacos
nacos-client
2.0.2
dubbo:
application:
version: 1.0.0
name: service-provider
registry:
address: nacos://111.52.99.114:18848?username=nacos&password=nacos
protocol:
name: dubbo
port: -1
provider:
timeout: 30000
:对于需要认证的nacos,使用url拼接用户名密码。
@EnableDubbo(scanBasePackages = "cn.bingo.lottery")
@SpringBootApplication
public class DempApplication {
public static void main(String[] args) {
SpringApplication.run(DempApplication.class,args);
}
}
//服务导出
@DubboService(version = "1.0.0",interfaceClass = IActivityBooth.class,retries = 0)
public class ActivityBooth implements IActivityBooth {
}
//服务引用
@DubboReference(version = "1.0.0",timeout =3000 )
private IActivityBooth activityBooth;
服务注册成功,nacos控制台可以看到服务列表,服务调用正常。如图:
com.alibaba.cloud
spring-cloud-starter-dubbo
com.alibaba.nacos
nacos-client
org.apache.dubbo
dubbo
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
com.alibaba.nacos
nacos-client
org.apache.dubbo
dubbo
spring-context
org.springframework
com.alibaba.nacos
nacos-client
dubbo.application.name=service-provider
dubbo.scan.base-packages=cn.service.test.api
spring:
application:
name: {应用名称}
cloud:
nacos:
discovery:
server-addr: 111.52.99.114:18848
username: nacos
password: nacos
//服务引用
@DubboReference(version = "1.0.0",retries = 0)
private ProductApi productApi;
//服务导出
@DubboService(version = "1.0.0",interfaceClass = ProductApi.class,retries = 0)
@Slf4j
public class ProductApiImpl implements ProductApi {}
可以看到这种接入,dubbo2.0的接口级对齐了springcloud的服务级。