注册中心Eureka:

新建项目stu-eureka:

StuEurekaApplication:

package com.demo.stueureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication
@EnableEurekaServer
public class StuEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(StuEurekaApplication.class, args);
} }

application.yml:

server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka

pom.xml:

<?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> <groupId>com.demo</groupId>
<artifactId>stu-eureka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>stu-provider</name>
<description>Demo project for Spring Boot</description>
<!-- 引入spring boot的依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- 引入spring cloud的依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 添加spring-boot的maven插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

配置安全:

在pom.xml中加入如下的依赖:(但是建议springBoot的版本为1.2或者更高,一般1.5左右可以)

 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

更改yml的配置如下:

security:
basic:
enabled: true
user:
name: user
password: password123
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://user:password123@localhost:8761/eureka
server:
enable-self-preservation: false #关闭自我保护
eviction-interval-timer-in-ms: 60

服务提供者:

新建项目stu-provider:

StuProviderApplication:

package com.demo.stuprovider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
@EnableEurekaClient
//@EnableDiscoveryClient//两者任选
public class StuProviderApplication { public static void main(String[] args) {
SpringApplication.run(StuProviderApplication.class, args);
} }

StudentController

package com.demo.stuprovider.controller;

import com.demo.stuprovider.entity.Student;
import com.demo.stuprovider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController
@RequestMapping("/")
public class StudentController { @Autowired
private StudentService studentService; @RequestMapping("teststu")
public String teststu() { return "kjlklkll"; }
@GetMapping("/getAll/{id}")
public Student getAll(@PathVariable("id")Integer id){
System.out.println("stu-provide:localhost:7900==>消费者查询学生时间:"+new Date().toLocaleString());
Student stu = studentService.getAllStu(id);
return stu;
}
}

Student

package com.demo.stuprovider.entity;

public class Student {

    private Integer id;
private String name;
private Integer age;
private String password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

StudentMapper

package com.demo.stuprovider.mapper;

import com.demo.stuprovider.entity.Student;
import org.apache.ibatis.annotations.Mapper; @Mapper
public interface StudentMapper {
public Student getAllStu(Integer id);
}

StudentService

package com.demo.stuprovider.service;

import com.demo.stuprovider.entity.Student;

public interface StudentService {
public Student getAllStu(Integer id);
}

StudentServiceImpl

package com.demo.stuprovider.service.impl;

import com.demo.stuprovider.entity.Student;
import com.demo.stuprovider.mapper.StudentMapper;
import com.demo.stuprovider.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service
public class StudentServiceImpl implements StudentService { @Resource
private StudentMapper studentMapper; @Override
public Student getAllStu(Integer id) {
return studentMapper.getAllStu(id);
}
}

Student.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo.stuprovider.mapper.StudentMapper"> <select id="getAllStu" parameterType="java.lang.Integer" resultType="com.demo.stuprovider.entity.Student">
select id,name,age,password from student where id = #{id}
</select> </mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <settings>
<!-- 配置关闭缓存 -->
<setting name="cacheEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="useGeneratedKeys" value="true"/>
<setting name="defaultExecutorType" value="REUSE"/>
<!-- 事务超时时间 -->
<setting name="defaultStatementTimeout" value="600"/>
</settings> <typeAliases>
<package name="com.home.entity" />
<!--<typeAlias type="Account" alias="user" />-->
</typeAliases>
<!--<mappers>
<mapper resource="mapper/user.xml" />
</mappers>-->
</configuration>

application.yml:

eureka:
client:
service-url:
defaultZone: http://user:password123@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
hostname: localhost
ip-address: localhost
server:
port: 7900
spring:
application:
name: stu-provider
datasource:
url: jdbc:mysql://10.167.199.44:3306/test?useSSL=false
username: root
password: ****
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 20
minIdle: 50
maxActive: 80
maxWait: 10000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMills: 300000
thymeleaf:
prefix: classpath:/templates/**
suffix: .html
mybatis:
config-location: classpath:/mybatis/mybatis-config.xml
mapper-locations: classpath:/mapper/Student.xml

pom.xml:

<?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> <groupId>com.home</groupId>
<artifactId>stu-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>stu-provider</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.3.1.RELEASE</version>
</dependency> <dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
</dependency> <!-- 支持 @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency> <!--mybatis与mysql-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.25</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

结果如下:

这个时候我们的application的名称和status的显示都是很不清晰的,我们如过要让它显示的更加明白,可以更改yml的配置如下所示:

eureka:
client:
service-url:
defaultZone: http://user:password123@localhost:8761/eureka
instance:
hostname: localhost
ip-address: localhost
prefer-ip-address: true
instance-id: ${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}}} server:
port: 7900
spring:
application:
name: stu-provider

这时候我们会看到eureka报了警告如下:

这个翻译过来如下:

//紧急情况!Eureka可能错误地声称实例已经启动,而事实并非如此。续约低于阈值,因此实例不会为了安全而过期。

这个是eureka的自我保护机制,如果我们想关闭它的自我保护,可以加入如下的配置:

eureka:
server:
enable-self-preservation: false #关闭自我保护
eviction-interval-timer-in-ms: 60

服务消费者

新建项目stu-consumer:

ConsumerController

package com.consumer.stuconsumer.controller;

import com.consumer.stuconsumer.entity.Student;
import com.consumer.stuconsumer.feign.UserFeginClient;
import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @RestController
@RequestMapping("/")
public class ConsumerController { @Resource
private UserFeginClient userFeginClient; @RequestMapping("/getAll/{id}")
public Student getAll(@PathVariable("id") Integer id) {
Student stu = this.userFeginClient.getAll(id);
System.out.println(stu);
return stu;
} }

Student

package com.consumer.stuconsumer.entity;

public class Student {

    private Integer id;
private String name;
private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

HyStrixClientFactory

package com.consumer.stuconsumer.feign;

import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; @Component
public class HyStrixClientFactory implements FallbackFactory<UserFeginClient> { private static final Logger log = LoggerFactory.getLogger(HyStrixClientFactory.class); @Override
public UserFeginClient create(Throwable cause) {
log.info("factory的返回异常信息打印:"+cause);
return null;
}
}

HyStrixFallBackClient

package com.consumer.stuconsumer.feign;

import com.consumer.stuconsumer.entity.Student;
import org.springframework.stereotype.Component; @Component
public class HyStrixFallBackClient implements UserFeginClient{
@Override
public Student getAll(Integer id) {
return null;
}
}

UserFeginClient

package com.consumer.stuconsumer.feign;

import com.consumer.stuconsumer.entity.Student;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name="stu-provider", fallback=HyStrixFallBackClient.class,fallbackFactory = HyStrixClientFactory.class)
public interface UserFeginClient { //不支持getmapping
@RequestMapping("/getAll/{id}")
public Student getAll(@PathVariable("id")Integer id); }

StuConsumerApplication

package com.consumer.stuconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class StuConsumerApplication { public static void main(String[] args) {
SpringApplication.run(StuConsumerApplication.class, args);
}
}

application.yml:

server:
port: 9301
eureka:
client:
healthcheck:
enable: true
serviceUrl:
defaultZone: http://user:password123@localhost:8761/eureka
# defaultZone: http://eureka1:8761/eureka,http://eureka2:8762/eureka,http://eureka3:8763/eureka
instance:
hostname: localhost
ipAddress: localhost
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
spring:
application:
name: stu-consumer
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://10.167.199.44:3306/test?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8;useSSL=false
username: root
password: ****
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 30
maxWait: 10000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMills: 300000
validationQuery: SELECT 1 FROM DUAL
session:
store-type: none
# redis:
# host: 127.0.0.1
# port: 6379
# password: redis
# database: 0
# 配置ribbon
#stu-provide:
# ribbon:
#
## NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #配置规则 随机
# NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule #配置规则 轮询
## NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RetryRule #配置规则 重试
## NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule #配置规则 响应时间权重
## NFLoadBalancerRuleClassName: com.netflix.loadbalancer.BestAvailableRule #配置规则 最空闲连接策略
# ConnectTimeout: 500 #请求连接超时时间
# ReadTimeout: 1000 #请求处理的超时时间
# OkToRetryOnAllOperations: true #对所有请求都进行重试
# MaxAutoRetriesNextServer: 2 #切换实例的重试次数
# MaxAutoRetries: 1 #对当前实例的重试次数 hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
feign:
hystrix:
enabled: true

Spring Cloud的注册中心和服务者,消费者的构建的更多相关文章

  1. Spring Cloud Eureka 注册中心集群搭建,Greenwich 最新版!

    Spring Cloud 的注册中心可以由 Eureka.Consul.Zookeeper.ETCD 等来实现,这里推荐使用 Spring Cloud Eureka 来实现注册中心,它基于 Netfl ...

  2. spring cloud 服务注册中心eureka高可用集群搭建

    spring cloud 服务注册中心eureka高可用集群搭建 一,准备工作 eureka可以类比zookeeper,本文用三台机器搭建集群,也就是说要启动三个eureka注册中心 1 本文三台eu ...

  3. IDEA 创建Spring cloud Eureka 注册中心

    IDEA 创建Spring cloud Eureka 注册中心 一. 首先创建一个maven project Next之后填好groupId与artifactId,Next之后填好项目名与路径,点击F ...

  4. spring Cloud服务注册中心Eureka集群

    spring Cloud服务注册中心Eureka集群配置: 在application.yml文件加以下配置: server: port: 8761 tomcat: uri-encoding: UTF- ...

  5. Spring Cloud服务注册中心交付至kubernetes

    前言 服务发现原则: 各个微服务在启动时,会将自己的网络地址等信息注册到服务发现组件中,服务发现组件会存储这些信息 服务消费者可以从服务发现组件中查询到服务提供者的网络地址,并使用该地址来远程调用服务 ...

  6. Spring Cloud Eureka 注册中心 服务消费者 服务提供者之间的关系以及高可用之间的联系

    注册中心:提供服务的注册与查询(发现) 服务提供者:服务的提供方,提供服务的一方. 服务消费者:服务的消费方,使用服务的一方. 我们没有注册中心,服务提供者与服务消费者同样可以调用,通过spring中 ...

  7. 二、Spring Cloud之注册中心 Eureka

    前言 算是正式开始学习 spring cloud 的项目知识了,大概的知道Springcloud 是由众多的微服务组成的,所以我们现在一个一个的来学习吧. 注册中心,在微服务中算是核心了.所有的服务都 ...

  8. spring cloud Eureka注册中心集群搭建

    1.创建springcloud-eureka maven项目 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0&quo ...

  9. Spring Cloud之注册中心搭建

    一.注册中心服务端搭建 1)引入相关Maven坐标 <dependency> <groupId>org.springframework.cloud</groupId> ...

随机推荐

  1. pushf和popf

    pushf的功能是将标志寄存器的值压栈,而popf是从栈中弹出数据,送入标志寄存器中.

  2. Linux驱动之定时器在按键去抖中的应用

    机械按键在按下的过程中会出现抖动的情况,如下图,这样就会导致本来按下一次按键的过程会出现多次中断,导致判断出错.在按键驱动程序中我们可以这么做: 在按键驱动程序中我们可以这么做来取消按键抖动的影响:当 ...

  3. 28.Mysql权限与安全

    28.Mysql权限与安全28.1 Mysql权限管理 28.1.1 权限系统的工作原理对连接的用户进行身份认证,合法的用户通过认证,不合法的用户拒绝连接:对通过认证的合法用户赋予相应的权限,用户可以 ...

  4. 14. pt-kill

    pt-kill h=192.168.100.101,P=3306,u=admin,p=admin \--match-user "user01" \--match-host &quo ...

  5. linux学习第十二天 (Linux就该这么学)找到一本不错的Linux电子书,附《Linux就该这么学》章节目录

    本书是由全国多名红帽架构师(RHCA)基于最新Linux系统共同编写的高质量Linux技术自学教程,极其适合用于Linux技术入门教程或讲课辅助教材,目前是国内最值得去读的Linux教材,也是最有价值 ...

  6. windows 性能监视器

    转载地址:https://www.cnblogs.com/luo-mao/p/5872374.html

  7. centos 安装tmux

    安装tmux之前需要先安装一些支持的组件: yum install libevent-devel ncurses-devel 接下来就是下载源码包进行安装了,以1.6版本举例 wget http:// ...

  8. sass基础常用指南

    一.变量 $global-color:red; .nav{ background:$global-color; } 二.sass命名时横杠和下划线不区分 $global-color:yellow; . ...

  9. HNOI 2018 简要题解

    寻宝游戏 毒瘤题. 估计考试只会前30pts30pts30pts暴力然后果断走人. 正解是考虑到一个数&1\&1&1和∣0|0∣0都没有变化,&0\&0& ...

  10. Linux下强制杀死进程的方法

    常规篇: 首先,用ps查看进程,方法如下: $ ps -ef …… smx 1822 1 0 11:38 ? 00:00:49 gnome-terminal smx 1823 1822 0 11:38 ...