美文网首页
创建SpringCloud工程

创建SpringCloud工程

作者: 叫我小码哥 | 来源:发表于2018-10-08 12:23 被阅读0次

创建一个springcloud工程主要包括3部分注册中心,服务提供方,服务消费方3部分组成。
首先我们来创建一个Eureka作为祖册中心。
1.添加 pom依赖
2.编写项目配置

server.port=8761
eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

server.port 制定Eureka项目的启动端口号。
eureka.instance.hostname 制定Eureka项目的访问ip地址。
eureka.client.register-with-eureka 表示是否将自己注册到Eureka服务中。
eureka.client.fetch-registry 表示是否从Eureka中获取信息。
eureka.client.service-url.defaultZone 表示Eureka客户端 与服务端的通信地址。

3.在启动类上添加@EnableEurekaServer注解。

@EnableEurekaServer
@SpringBootApplication
public class ErurkaApplication {
    public static void main(String[] args) {
        SpringApplication.run(ErurkaApplication.class, args);
    }
}

然后我们创建一个springboot项目作为服务的提供着。
1.添加 pom依赖
2.编写项目配置

server.port=8080
spring.application.name=PROVIDE-ONE
eureka.client.service-url.defaultZone: http://localhost:8761/eureka/
eureka.instance.prefer-ip-address:true

3.编写代码

@EnableDiscoveryClient
@SpringBootApplication
public class TextApplication {
    public static void main(String[] args) {
        SpringApplication.run(TextApplication.class, args);
    }
}

最后编写服务消费者
1.添加 pom依赖
2.编写项目配置

server.port=8081
spring.application.name=springcloud-customer
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=true
eureka.client.service-url.defaultZone: http://localhost:8761/eureka/

3.编写代码

    @Autowired
    private RestTemplate restTemplate ;
    @Autowired
    private DiscoveryClient discoveryClient;

    public Book getBookById(Integer id){
        String providerName ="PROVIDE-ONE";
        List<ServiceInstance> instances= this.discoveryClient.getInstances(providerName);
        if(instances.isEmpty()){
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String url = serviceInstance.getHost()+":"+serviceInstance.getPort();
        return this.restTemplate.getForObject("http://"+url+"/item/"+id,Book.class);
    }

@EnableDiscoveryClient
@SpringBootApplication
public class Text1Application {
    public static void main(String[] args) {
        SpringApplication.run(Text1Application.class, args);
    }
}

相关文章

网友评论

      本文标题:创建SpringCloud工程

      本文链接:https://www.haomeiwen.com/subject/hhwdaftx.html