工具:IDEA
技术栈:
-
spring cloud;
- Eureka Server;
- ribbon;
- gateway;
- config;
- bus
-
mybatis;
其他工具使用:postman
步骤:
创建父工程 微服务中需要同时创建多个项目,先创建一个父工程,后续的工程都以这个工程为父,使用 Maven的聚合和继承。统一管理子工程的版本和配置。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L0sMk6qX-1634736764643)(C:UsershellnAppDataRoamingTyporatypora-user-imagesimage-20211020202352905.png)]
新建一个项目,对外提供查询用户的服务 首先创建moudle:4.0.0 com.zym zym-springcloud pom 1.0-SNAPSHOT eurekasever user-service consumer-demo zym-gateway config-server org.springframework.boot spring-boot-starter-parent 2.1.5.RELEASE 1.8 Greenwich.SR1 2.1.5 5.1.46 org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import tk.mybatis mapper-spring-boot-starter ${mapper.starter.version} mysql mysql-connector-java ${mysql.version} org.projectlombok lombok org.springframework.boot spring-boot-maven-plugin
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iUamzhwa-1634736764648)(C:UsershellnAppDataRoamingTyporatypora-user-imagesimage-20211020202609317.png)]
pom.xml文件:项目结构:zym-springcloud com.zym 1.0-SNAPSHOT 4.0.0 user-service org.springframework.boot spring-boot-starter-web tk.mybatis mapper-spring-boot-starter mysql mysql-connector-java org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-config org.springframework.cloud spring-cloud-bus org.springframework.cloud spring-cloud-stream-binder-rabbit org.springframework.boot spring-boot-starter-actuator com.github.pagehelper pagehelper-spring-boot-starter 1.2.3
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tgtNSrGZ-1634736764650)(C:UsershellnAppDataRoamingTyporatypora-user-imagesimage-20211020202728495.png)]
配置文件:spring:
cloud:
config:
#git仓库中配置文件的application一致
name: user
#git仓库中配置文件的profile一致
profile: dev
#git仓库分支一致
label: master
discovery:
# 使用配置中心
enabled: true
# 配置中心服务名
service-id: config-server
# 配置rabbitmq信息;如果是都与默认值一致则不需要配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
编写启动类:
package com.zym;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.zym.mapper")
@EnableDiscoveryClient
@EnableCircuitBreaker
public class UserSeverApplication {
public static void main(String[] args) {
SpringApplication.run(UserSeverApplication.class, args);
}
}
实体类:
package com.zym.pojo;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Table(name = "bill_")
public class Bill implements Serializable {
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getBillTime() {
return billTime;
}
public void setBillTime(Date billTime) {
this.billTime = billTime;
}
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getExplain() {
return explain;
}
public void setExplain(String explain) {
this.explain = explain;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public Date getDate1() {
return date1;
}
public void setDate1(Date date1) {
this.date1 = date1;
}
public Date getDate2() {
return date2;
}
public void setDate2(Date date2) {
this.date2 = date2;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_")
private Long id;
@Column(name = "title_")
private String title;
@Column(name = "bill_time_")
private Date billTime;
@Column(name = "type_id_")
private Long typeId;
@Column(name = "price_")
private Double price;
@Column(name = "explain_")
private String explain;
@Transient
private String typeName;
@Transient
private Date date1;
@Transient
private Date date2;
}
dao:
package com.zym.mapper; import com.zym.pojo.Bill; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface BillMapper extends Mapperservice:{ }
package com.zym.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zym.mapper.BillMapper;
import com.zym.pojo.Bill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BillService {
@Autowired
private BillMapper billMapper;
public List list() {
return billMapper.selectAll();
}
public int add(Bill b) {
return billMapper.insert(b);
}
public Bill get(Long id) {
return billMapper.selectByPrimaryKey(id);
}
public int update(Bill b) {
return billMapper.updateByPrimaryKeySelective(b);
}
public int delete(Long id) {
return billMapper.deleteByPrimaryKey(id);
}
public PageInfo listPage(Bill b, int pageNum, int pageSize) {
return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> {
billMapper.select(b);
});
}
}
控制类:
package com.zym.controller;
//import com.github.pagehelper.PageInfo;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zym.pojo.Bill;
import com.zym.pojo.BillType;
import com.zym.service.BillService;
import com.zym.service.TypeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/bill")
@DefaultProperties(defaultFallback = "defaultFallback")
@RefreshScope
public class BillController {
@Resource
private TypeService typeService;
@Resource
private BillService billService;
@Value("${test.name}")
private String name;
public String defaultFallback() { return "默认提示:对不起,网络太拥挤了!"; }
@RequestMapping("/list")
public List list() {
System.out.println("配置中心配置的test.name = " + name);
List list = billService.list();
return list;
}
@RequestMapping("/toAdd")
public String toAdd(Model model) {
List types = typeService.list();
model.addAttribute("types", types);
return "/bill/add";
}
@ResponseBody
@RequestMapping("/add")
public Integer add(@RequestBody Bill b) {
return billService.add(b);
}
@RequestMapping("/delete/{id}")
public Integer delete(@PathVariable("id") Long id) {
return billService.delete(id);
}
@RequestMapping("/{id}")
public Bill queryById(@PathVariable("id") Long id) {
return billService.get(id);
}
@ResponseBody
@RequestMapping("/update/{id}")
public Integer update(@PathVariable("id") Long id, @RequestBody Bill b) {
b.setId(id);
return billService.update(b);
}
}
创建注册中心项目
Eureka负责管理、记录服务提供者的信息。服务调用者无需自己寻找服务,而是把自己的需求告诉 Eureka,然后Eureka会把符合你需求的服务告诉你。
同时,服务提供方与Eureka之间通过 “心跳” 机制进行监控,当某个服务提供方出现问题,Eureka自然会把它从服 务列表中剔除。
这就实现了服务的自动注册、发现、状态监控。
项目结构[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4KHhDYGd-1634736764654)(C:UsershellnAppDataRoamingTyporatypora-user-imagesimage-20211020210638176.png)]
pom.xml文件配置文件:zym-springcloud com.zym 1.0-SNAPSHOT 4.0.0 eurekasever org.springframework.cloud spring-cloud-starter-netflix-eureka-server
server:
port:
10086
spring:
application:
name: eureka-server
eureka:
client:
service-url: # eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址
defaultZone: HTTP://127.0.0.1:10086/eureka # 不注册自己
register-with-eureka: false # 不拉取服务
fetch-registry: false
启动类:
package com.zym;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@EnableEurekaServer
@SpringBootApplication
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
创建网关项目:
Spring Cloud Gateway组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。 Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点IP端口信息,从而加强安全保护。Spring Cloud Gateway本身也是一个微服务,需要注册到Eureka服务注册中心。
网关的核心功能是:过滤和路由
项目结构: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J5cF0O6s-1634736764656)(C:UsershellnAppDataRoamingTyporatypora-user-imagesimage-20211020211551940.png)] pom.xml文件配置文件:zym-springcloud com.zym 1.0-SNAPSHOT 4.0.0 zym-gateway org.springframework.cloud spring-cloud-starter-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client
server:
port: 8086
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
#路由的id,可以随意些
- id: user-service-rote
#代理的微服务地址
#uri: http://127.0.0.1:9091
uri: lb://user-service
#路由断言:可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 1:去除一个路径,2:去除2路径,以此类推
- StripPrefix=1
# default-filters:
# - AddResponseHeader=X-Response-Foo, Bar
# - AddResponseHeader=myname, lxs
globalcors:
corsConfigurations:
'[/**]':
#allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- "http://docs.spring.io"
allowedMethods:
- GET
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S
ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 1 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 1 # 重试多少次服务
启动类:
package com.zym;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
thread:
timeoutInMilliseconds: 6000 #服务降级超时时间,默认1S
ribbon:
ConnectTimeout: 1000 # 连接超时时长
ReadTimeout: 2000 # 数据通信超时时长
MaxAutoRetries: 1 # 当前服务器的重试次数
MaxAutoRetriesNextServer: 1 # 重试多少次服务
### 启动类:
```java
package com.zym;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
关于config配置中心与bus的内容下一章继续!



