搭建springcloud单机环境下的注册中心,服务提供者,服务消费者

在本地环境搭建过程中出现的问题,jar的依赖找不到,建议去寻找存在的依赖,本地环境是jdk1.8,maven3.5.4,springcloud版本Finchley.RELEASE,springboot版本2.0.5.RELEASE,如果依据博客搭建显示依赖找不到,请根据springcloud找到合适的版本,如下,仅供参考

 

 本项目是一个父工程,父工程下面有三个子工程,关于项目结构搭建在前面的博客中有说明

父工程依赖如下

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <modules>
        <module>qiuxie-eureka</module>
        <module>qiuxie-provider</module>
        <module>qiuxie-consumer</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <groupId>com.parent</groupId>
    <artifactId>qiuxie-parent</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
                <version>2.0.0.RELEASE</version>
            </dependency>
            <!--客户端-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
                <version>2.0.0.RELEASE</version>
            </dependency>
            <!--web依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.0.1.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <!--编译插件-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <!--打包插件-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

接着第一个子工程是eureka注册中心

pom文件如下

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>qiuxie-parent</artifactId>
        <groupId>com.parent</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.eureka</groupId>
    <artifactId>qiuxie-eureka</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>


</project>

eureka注册中心的项目结构

 

 

 

 下面给出代码

启动类代码
package com.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 19:48
 */
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class,args);
    }
}
配置文件
server.port=8761
spring.application.name=springcloud-eureka
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

查询eureka注册中心,浏览器打开localhost:8761,端口可以随机设置

第二是服务提供者

本次的服务提供者的功能是根据ip查询ip对应的城市信息,所以结构上有些复杂,觉得麻烦的话,可以自行简化

首先是服务提供者的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>qiuxie-parent</artifactId>
        <groupId>com.parent</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.provider</groupId>
    <artifactId>qiuxie-provider</artifactId>
    <dependencies>
        <!--客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
        <!--判断空的用法  -->
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

</project>

接下来是项目结构部分

 

 代码完整如下

package com.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 19:56
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class,args);
    }
}

package com.provider.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:12
 */
@Configuration
public class ProviderConfig {

    @Bean
    public RestTemplate getRestTemple(){
        return new RestTemplate();
    }
}

package com.provider.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.provider.service.QueryIpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:16
 */
@Controller
@RequestMapping("/queryIp")
public class QueryIpController {

    @Autowired
    private QueryIpService qiuxiequeryip;

    @RequestMapping("/queryIpCity/{ip}")
    @ResponseBody
    public String queryIpCity(@PathVariable String ip){
        JSONObject ipCityByIp = qiuxiequeryip.getIpCityByIp(ip);
        return ipCityByIp.toJSONString();
    }
}


package com.provider.service;

import com.alibaba.fastjson.JSONObject;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:03
 */
public interface QueryIpService {

    JSONObject getIpCity();

    JSONObject getIpCityByIp(String ip);

    String queryCityByIp(String ip);
}


package com.provider.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.provider.service.QueryIpService;
import org.springframework.stereotype.Service;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:06
 */
@Service
public abstract class GeneralQueryIpServiceImpl implements QueryIpService {
    @Override
    public JSONObject getIpCity() {
        return null;
    }

    @Override
    public JSONObject getIpCityByIp(String ip) {
        return null;
    }

    @Override
    public String queryCityByIp(String ip) {
        return null;
    }
}



package com.provider.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:08
 */
@Service("qiuxiequeryip")
public class QiuXieQueryIpServiceImpl extends GeneralQueryIpServiceImpl {
    private static final Logger logger= LoggerFactory.getLogger(QiuXieQueryIpServiceImpl.class);

    @Autowired
    private  RestTemplate restTemplate;

    @Override
    public JSONObject getIpCityByIp(String ips) {
        logger.info("入参:"+ips);
        JSONObject object1 = new JSONObject();
        String ipp=ips;
        if (StringUtils.isEmpty(ipp)){
            String ip="127.0.0.1";
            String city="ip地址为null";
            object1.put("ip", ip);
            object1.put("city",city);
            return object1;
        }
        String url = "http://ip.dhcp.cn/?ip=" + ipp;
        URI uri = URI.create(url);
        String str = null;
        try {
            str = restTemplate.getForObject(uri, String.class);
            logger.info("调用接口返回参数:"+str);
        } catch (RestClientException e) {
            String ip="127.0.0.1";
            String city="城市信息未能获取";
            object1.put("ip", ip);
            object1.put("city",city);
            return object1;
        }
        JSONObject jsonObject = JSON.parseObject(str);
        JSONObject address = JSON.parseObject(jsonObject.getString("Address"));
        JSONObject object=new JSONObject();
        object.put("country",address.getString("Country"));
        object.put("city",address.getString("City"));
        object.put("provice",address.getString("Province"));
        object.put("ip",jsonObject.getString("IP"));
        object.put("isp",jsonObject.getString("ISP"));
        object.put("address",getAddress(address,jsonObject.getString("ISP")));
        return object;
    }

    protected String getAddress(JSONObject jsonObject,String isp){
        String address=null;
        if (StringUtils.isNotEmpty(jsonObject.getString("Country"))){
            address=jsonObject.getString("Country");
        }
        if (StringUtils.isNotEmpty(jsonObject.getString("Province"))){
            address=address+jsonObject.getString("Province");
        }
        if (StringUtils.isNotEmpty(jsonObject.getString("City"))){
            address=address+jsonObject.getString("City");
        }
        if (StringUtils.isNotEmpty(isp)){
            address=address+isp;
        }
        if (StringUtils.isEmpty(address)){
            address="地址飘到火星了";
        }
        return address;

    }
}




server.port=1000

spring.application.name=qiuxie-provider
#注册到eureka注册中心,如果是注册到集群就用逗号连接多个,单实例写上一个就好
eureka.client.service-url.defaultZone=http://localhost:8761/eureka


logging.level.com.provider=debug
logging.level.web=debug
spring.devtools.add-properties=false

最后是服务消费者,结构相对简单些

pom文件如下

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>qiuxie-parent</artifactId>
        <groupId>com.parent</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.consumer</groupId>
    <artifactId>qiuxie-consumer</artifactId>
    <dependencies>
        <!--客户端-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加fastjson依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
    </dependencies>
</project>

接着是项目结构

 

服务消费者完整代码

package com.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:35
 */
@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }
}


package com.consumer.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-27 1:45
 */
@Configuration
public class ConsumerConfig {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}


package com.consumer.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author yourheart
 * @Description
 * @create 2021-06-26 20:36
 */
@Controller
public class ConsumerController {

    @Autowired
    private  RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/queryIp")
    @ResponseBody
    public String queryIp(String ip){
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("qiuxie-provider");
        //从多个事实例中选中一个
        ServiceInstance serviceInstance = serviceInstanceList.get(0);
        //从元数据信息获取host port
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url="http://"+host+":"+port+"/queryIp/queryIpCity/"+ip;
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        return "打印消费者获取的数据:"+jsonObject.toString();
    }
}


server.port=2000

spring.application.name=qiuxie-consumer
#注册到eureka注册中心,如果是注册到集群就用逗号连接多个,单实例写上一个就好
eureka.client.service-url.defaultZone=http://localhost:8761/eureka


logging.level.com.provider=debug
logging.level.web=debug
spring.devtools.add-properties=false

  

服务消费者调用服务提供者接口

http://127.0.0.1:2000/queryIp?ip=你需要查询的ip

eureka查询到信息

 

posted @ 2021-07-05 00:13  不忘初心2021  阅读(110)  评论(0编辑  收藏  举报