Spring cloud 之Netflix Eureka系列一(Ribbon实现用户服务调用)

一、项目总体介绍

         1、项目功能介绍(系统用的jar包版本1.5.8)

                  1.1、本次项目实现用户服务客户端(消费者)调用用户服务生产者(提供user服务)实现对数据库的相关操作

               

         2、系统模块介绍(项目总共分为4个模块组成)

                   2.1、user-api (定义服务需要的接口(增删查改),以及消费者生产者共有的东西)

                   2.2、eureka-registry(服务注册中心)

                   2.3、user-service-provider(服务提供者)

                   2.4、user-service-consumer(服务消费者)

          3、服务关联关系(这里引用dubbo 的架构图)

               

                  关联关系主要有两点:

                          第一点是:所有的服务都往注册中心进行注册(包括生产者和消费者,Eureka注册中心除外)

                          第二点是:消费者调用服务者提供服务

 

 

         二、项目代码及结构展示

            2.1、user-api

                   2.1.1、项目目录结构

                            

                   2.1.2、项目代码

                              

package com.gpdi.user.entity;

/**
 *
 * @desc:用户实体类(POJO/VO/Domain)
 *
 */
public class User {

    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

----------------------------这是一条分割线-------------------------------------------

import java.util.List

/**
 * @description:提供用户服务的接口
 *
 */
public interface UserService {

    /**
     * 添加一个用户
     */
    public void addUser(User user);

    /**
     * 查询用户信息
     */
    public List<User> getAllUser();

}

          2.2、eureka-registry

                     2.2.1、项目目录结构

                                  

                2.2.2、项目代码

                          

--------------------启动入口(Appliction)---------------------------------------
package com.gpdi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

---------------------配置文件(application.properties)-------------------------



#HTTP访问端口
server.port=7000

#是否将服务注册到注册中心,这是服务注册中心,禁止自我注册
eureka.client.register-with-eureka=false

#是否从Eureka server 获取注册信息,注册中心的服务器,没有必要再去检索服务
eureka.client.fetch-registry=false

#设置服务的默认注册地址
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/

#设为false,关闭自我保护
eureka.server.enable-self-preservation=false

#清理间隔(单位毫秒,默认是60*1000)
eureka.server.eviction-interval-timer-in-ms=10000


-------------------------环境依赖-----------------------------------------
  <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>

  <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-eureka-server</artifactId>
  </dependency>
  <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

         2.3、user-service-provider

                    2.3.1、项目目录结构

                            

 2.3.2、项目代码

                 

--------------配置文件(application.properties)-----------------------------

#配置Eureka服务

spring.application.name = user-service-provider

## Eureka 注册中心服务器端口
eureka.server.port = 7000

## 服务提供方端口
server.port = 7071

## Eureka Server 服务 URL,用于客户端注册
eureka.client.serviceUrl.defaultZone=\
  http://localhost:${eureka.server.port}/eureka

## Management 安全失效
management.security.enabled = false


#durid配置(http://localhost:8087/dcjk/druid/index.html)
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.druid.url = jdbc:mysql://localhost:3306/eureka-user?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.druid.username=root
spring.datasource.druid.password=root

# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
#spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
spring.datasource.druid.useGlobalDataSourceStat=true


#mybatis设置

###配置myBatis映射
#mybatis-plus.mapper-locations=classpath:mybatis/mapper/*.xml
#mybatis-plus.typeAliasesPackage=com.gpdi.user.entity

##配置mybatis驼峰
#mybatis-plus.configuration.map-underscore-to-camel-case: true



-----------------------核心环境依赖---------------------------------------



   <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-eureka-server</artifactId>
         <version>1.3.5.RELEASE</version>
    </dependency>


-----------------------实现类UserImpl--------------------------------------
      

package com.gpdi.service;

import com.gpdi.user.entity.User;
import com.gpdi.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;


import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Override
    public void addUser(User user) {
        System.out.println("添加成功" + user);
        String name = user.getName();
        String sql = "insert into user values(null,#{" + name + "})";
        jdbcTemplate.execute(sql);

    }

    @Override
    public List<User> getAllUser() {

        return jdbcTemplate.query("select * from user ", new BeanPropertyRowMapper(User.class));

    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

}



---------------------------Controller-------------------------------

package com.gpdi.controller;

import com.gpdi.service.UserServiceImpl;
import com.gpdi.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class UserController {


    /**
     * @param user User
     * @return 如果保存成功的话,返回{@link User},否则返回<code>null</code>
     */
    @PostMapping("/user/addUser")
    public void saveUser(@RequestBody User user) {
        userService.addUser(user);
    }

    /**
     * @return 所有的用户数据
     */
    @GetMapping("/user/list")
    public List<User> list() {
        return userService.getAllUser();
    }

    @Autowired
    private UserServiceImpl userService;
}

---------------------------启动文件-------------------------------

package com.gpdi;

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

@EnableEurekaServer
@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}


2.4、user-service-consumer

             2.4.1、项目目录结构

                      

               2.4.1、项目代码展示

                           

---------------------------------Controller层--------------------------------------

package com.gpdi.controller;//package com.gpdi.controller;

import com.gpdi.service.UserServiceProxy;
import com.gpdi.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class UserController {

    @Autowired
    private UserServiceProxy userService;

    /**
     *
     * 保存一个用户
     */
    @PostMapping("/user/save")
    public void saveUser(@RequestParam String name) {
        User user = new User();
        user.setName(name);
        userService.addUser(user);

    }

    /**
     *
     *
     * @return 所有的用户数据
     */
    @GetMapping("/user/list")
    public List<User> list() {
        return userService.getAllUser();
    }


    /**
     * @desc:获取请求服务实例
     *
     */
    @GetMapping("/consumer")
    public String dc() {
         ServiceInstance serviceInstance = loadBalancerClient.choose("user-service-provider");
        //获取一个实例的具体Ip地址和端口
         String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
         System.out.println(" 服务的请求地址 "+url);
        // return restTemplate.getForObject(url, String.class);
        return url;
    }

    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    RestTemplate restTemplate;


}
-----------------------------------Service实现层------------------------------------

package com.gpdi.service;//package com.gpdi.service;


import com.gpdi.user.entity.User;
import com.gpdi.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @desc:UserServiceProxy 实现
 *
 */
@Service
public class UserServiceProxy implements UserService {

    private static final String PROVIDER_SERVER_URL_PREFIX = "http://user-service-provider";

    /**
     * 通过 REST API 代理到服务器提供者
     */
    @Autowired
    private RestTemplate restTemplate;



    @Override
    public void addUser(User user) {
        restTemplate.postForObject(PROVIDER_SERVER_URL_PREFIX + "/user/save", user, User.class);
    }

    @Override
    public List<User> getAllUser() {
        return restTemplate.getForObject(PROVIDER_SERVER_URL_PREFIX + "/user/list", List.class);
    }
}

------------------------------Application层---------------------------------
package com.gpdi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.client.RestTemplate;


@EnableDiscoveryClient
@SpringBootApplication
public class Application {
    @LoadBalanced
	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	public static void main(String[] args) {

		SpringApplication.run(Application.class, args);
	}
}
--------------------------------环境依赖---------------------------

  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>1.4.5.RELEASE</version>
 </dependency>
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
-----------------------------系统配置文件------------------------------------
spring.application.name=user-service-consumer
server.port=8081
eureka.client.serviceUrl.defaultZone=http://localhost:7000/eureka/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值