=============================================================
服务提供者与服务消费者
技术交流群:170933152
-------------------------------------------------------------
1 概念
-------------------------------------------------------------
图:
服务提供者消费者演示.png
服务提供者消费者概念.png
-------------------------------------------------------------
2 编写一个服务提供者
-------------------------------------------------------------
2.1这里首先进入:
http://start.spring.io/ 自动生成一个项目
MavenProject java SpringBoot 1.4.7
这里看到:
Release 表示 是正式的版本.
RC stands for Release Candidate 表示 后选版本
M stands for milestone 表示里程碑版本.
一般而言, 稳定性由上而下, 依次降低.
这里咱们用release版本,1.5.9
group:com.credream.cloud
artifactId:credreamservice-simple-provider-user
Dependencies:
这里需要依赖,web(springMvc),JPA(SpringData),H2()
H2是一个短小精干的嵌入式数据库引擎,主要的特性包括:
1、免费、开源、快速;
2、嵌入式的数据库服务器,支持集群;
3、提供JDBC、ODBC访问接口,提供基于浏览器的控制台管理程序;
4、Java编写,可使用GCJ和IKVM.NET编译;
5、短小精干的软件,1M左右。
几个嵌入式数据库的对比:
H2数据库.jpg
------------------------------------------
配置以后,点击GenerateProject然后生成一个SpringCloud项目:
credreamservice-simple-provider-user.zip
然后再生成一个,一个做服务发现者,一个做服务消费者.
-------------------------------------------------------------
3 编写一个服务消费者
-------------------------------------------------------------
1.先导入刚才生成的Maven项目
2.可以看看pom.xml
然后E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\resources\static
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\resources\templates
这两个可以删除,没有用
------------------------
3.写一下sql:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\resources\schema.sql
drop table user if exists;
create table user(
id bigint generated by default as identity,
username varchar(40),
name varchar(20),
age int(3),
balance decimal(10,2),
primary key(id)
);
---------------------
4.然后再写一个sql来插入数据:
insert into user(id,username, name, age, balance) values(1,'user1', '张三', 20, 100.00);
insert into user(id,username, name, age, balance) values(2,'user2', '李四', 20, 100.00);
insert into user(id,username, name, age, balance) values(3,'user3', '王五', 20, 100.00);
insert into user(id,username, name, age, balance) values(4,'user4', '马六', 20, 100.00);
--------------------------
5.写完sql来写一下实体类:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\entity\User.java
package com.credream.cloud.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
//1.因为用到了spring data jpa,所以这里用到一些jpa的注解
@Entity
public class User implements Serializable {
@Id
//2.主键自增长
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String username;
@Column
private String name;
@Column
private Short age;
@Column
private BigDecimal balance;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return this.age;
}
public void setAge(Short age) {
this.age = age;
}
public BigDecimal getBalance() {
return this.balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
---------------------------------------
6.写DAO
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\repository\UserRepository.java
package com.credream.cloud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.credream.cloud.entity.User;
//1.注意这里之所以叫Repository是DAO,是因为这里Repository是一种
//JPA中的用法,他在这里被称为资源库
//2.@Repository加上这个注解,表示他是一个DAO
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
--------------------------------------
7.写Controller这里例子比较简单,就不写service了
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\UserController.java
package com.credream.cloud;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.credream.cloud.entity.User;
import com.credream.cloud.repository.UserRepository;
//1.由于例子挺简单,这里只用controller调用DAO
//3.注意这个:
//@RestController也是一个组合注解:
//点进去看看:
//@Target(ElementType.TYPE)
//@Retention(RetentionPolicy.RUNTIME)
//@Documented
//@Controller
//@ResponseBody
//public @interface RestController {
//其实这里相当于加了
//ResponseBody和Controller注解对吧.
//
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
//2.这里说一下这个注解:
//@GetMapping
//这个其实是一个组合注解
//点进去看看源码:
/* @author Sam Brannen
* @since 4.3
* @see GetMapping
* @see PostMapping
* @see PutMapping
* @see DeleteMapping
* @see RequestMapping
*/
// @Target(ElementType.METHOD)
// @Retention(RetentionPolicy.RUNTIME)
// @Documented
// @RequestMapping(method = RequestMethod.PATCH)
// public @interface PatchMapping {
//可以看到除了:@GetMapping还有PostMapping,PutMapping等
//其实他相当于:
//@RequestMapping(value="/xxx",method=RequestMethod.GET)
//相当于这个
//同样,post也是这样
@GetMapping("/simple/{id}")
public User findById(@PathVariable Long id) {
return this.userRepository .findOne(id);
}
}
-----------------------
8.最后来写一写配置文件,这里他可以用properties文件,这里
我使用yml,他是一个结构化的文件风格
把这个:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\resources\application.properties
改成:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\resources\application.yml
server:
port: 7900 //端口
spring:
jpa: //配置一下jpa
generate-ddl: false //启动的时候是否生成ddl语句,这里false,因为咱们自己写了ddl语句了
show-sql: true//需要显示sql
hibernate://因为springjpa,依赖于hibernate,所以这里配置一下hibernate
ddl-auto: none//由于ddl,咱们自己写的,这里配置一下,让他对ddl不做处理
datasource:
platform: h2//数据源,这里使用h2数据库
schema: classpath:schema.sql//这里配置建表语句,这里用classpath下面的
data: classpath:data.sql//这个是数据语句,就是插入数据的语句
logging://配置一下日志
level:
root: INFO//根级别用info
org.hibernate: INFO//hibernate的用info
org.hibernate.type.descriptor.sql.BasicBinder: TRACE //注意这两个,是跟上面的内容是有一定联系的
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE//目的是为了打印sql和上面的那个showsql是有联系的
com.credream: DEBUG//配置自己的日志
----------------------------------
这里咱们也可以点进去:
platform: h2//数据源,这里使用h2数据库
schema: classpath:schema.sql//这里配置建表语句,这里用classpath下面的
data
这里的schema,看看他的默认值是什么:
在:
package org.springframework.boot.autoconfigure.jdbc;
这个包里的:
DataSourceInitializer这个类中:
private void runSchemaScripts() {
List<Resource> scripts = getScripts("spring.datasource.schema",
this.properties.getSchema(), "schema");
这里可以看到,如果没有配置,那么默认的就是:
schema
-----------
当然data.sql,默认的也是data
所以下面这些是可以不用配置的对吧,因为他有默认值
--------------------------------------
9.然后改一下:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\UserController.java
他的位置:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\controller\UserController.java
改到这里:
package com.credream.cloud.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.credream.cloud.entity.User;
import com.credream.cloud.repository.UserRepository;
//1.由于例子挺简单,这里只用controller调用DAO
//3.注意这个:
//@RestController也是一个组合注解:
//点进去看看:
//@Target(ElementType.TYPE)
//@Retention(RetentionPolicy.RUNTIME)
//@Documented
//@Controller
//@ResponseBody
//public @interface RestController {
//其实这里相当于加了
//ResponseBody和Controller注解对吧.
//
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
//2.这里说一下这个注解:
//@GetMapping
//这个其实是一个组合注解
//点进去看看源码:
/* @author Sam Brannen
* @since 4.3
* @see GetMapping
* @see PostMapping
* @see PutMapping
* @see DeleteMapping
* @see RequestMapping
*/
// @Target(ElementType.METHOD)
// @Retention(RetentionPolicy.RUNTIME)
// @Documented
// @RequestMapping(method = RequestMethod.PATCH)
// public @interface PatchMapping {
//可以看到除了:@GetMapping还有PostMapping,PutMapping等
//其实他相当于:
//@RequestMapping(value="/xxx",method=RequestMethod.GET)
//相当于这个
//同样,post也是这样
@GetMapping("/simple/{id}")
public User findById(@PathVariable Long id) {
return this.userRepository .findOne(id);
}
}
----------------------
10.这里注意一个地方:
在springboot项目中:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\cloud\CredreamserviceSimpleProviderUserApplication.java
他的启动类是带有main方法的类:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user
\src\main\java\com\credream\cloud\
CredreamserviceSimpleProviderUserApplication.java
注意这个类,需要放在:最外层的包里面:
这里是:com\credream\cloud
如果放到其他的包里,比如
com\credream\cloud\controller等等,
那么子包里的注解就不起作用了
因为他默认扫描,当前包,和当前包下面的子包中的注解
---------------------------
11.启动一下:
然后访问:
http://localhost:7900/simple/1
可以看到:
{"id":1,"username":"user1","name":"张三","age":20,"balance":100.00}
已经把数据都打印出来了
--------------------------------------
12.http://localhost:7900/simple/2
这个也可以对吧
----------------------
13.看一下日志:
这里如果你的控制台上显示的是红颜色的:INFO...
那么可以做个配置:
找到那个debug的图标,选择:
Debug Configurations
找到:
spring boot app:
com.credream.cloud.CredreamserviceSimpleProviderUserApplication
找到以后:
把:ANSI console output勾去掉就可以了
-02-12 21:30:06.362 INFO 1172 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2018-02-12 21:30:06.591 INFO 1172 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-02-12 21:30:06.591 INFO 1172 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2976 ms
2018-02-12 21:30:06.770 INFO 1172 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-02-12 21:30:06.777 INFO 1172 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-02-12 21:30:06.778 INFO 1172 --- [
------------------------------------------
再跑程序的时候,控制台就都是黑的了,红的可能会copy出来会有问题,会
乱码
-----------------------------
14.接下来再写一个:
服务消费者:
------------------
15.导入准备的:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie
注意如果想从E:\SpringCloudWorkSpace\credreamservice-simple-provider-user
\credreamservice-simple-provider-user
来重复利用,那么可以这样:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\pom.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.credream.cloud</groupId>
//1.这里改成:credreamservice-simple-provider-movie
<artifactId>credreamservice-simple-provider-movie</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
//2.这里也改成:
//credreamservice-simple-provider-movie
<name>credreamservice-simple-provider-movie</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
--------------------
16.好,导入以后,咱们开始写:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com
\credream\cloud\controller\MovieController.java
package com.credream.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.credream.cloud.entity.User;
//1.这里,添加rest注解,生成restful风格api
@RestController
public class MovieController {
//2.自动装配,通过restTemplate获取服务提供者提供的api
@Autowired
private RestTemplate restTemplate;
//3.mapping
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://localhost:7900/simple/"+id, User.class);
}
}
-----------------
17.
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud\entity\User.java
package com.credream.cloud.entity;
import java.math.BigDecimal;
public class User {
private Long id;
private String username;
private String name;
private Short age;
private BigDecimal balance;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return this.age;
}
public void setAge(Short age) {
this.age = age;
}
public BigDecimal getBalance() {
return this.balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
-----------------------------------
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud\credreamservicesimpleprovideruser\
CredreamserviceSimpleProviderUserApplication.java
把这个放到最外面:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud\
CredreamserviceSimpleProviderUserApplication.java
18.配置一下:
application.properties-->application.yml
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\resources\application.yml
server:
port: 7901
19.
然后启动一下试试
报错了:
Description:
Field restTemplate in com.credream.cloud.controller.
MovieController required a bean of type
'org.springframework.web.client.RestTemplate' that could not
be found.
Action:
Consider defining a bean of type 'org.springframework.web.
client.RestTemplate' in your configuration.
这是因为,咱们这个:
restTemplate还没有new呢对吧,
来:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud\CredreamserviceSimpleProviderUserApplication.java
改一改:
package com.credream.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class CredreamserviceSimpleProviderUserApplication {
//1.添加一个方法:
//这里添加restTemplate方法,注意这个Bean注解,根据引入的类,新建一个对象,
//返回,这里方法的名字,可以随便起,但是应该跟:
//@Autowired controller中的自动装配对应起来
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(CredreamserviceSimpleProviderUserApplication.class, args);
}
}
------------------------------------------
20.然后再跑跑:
首先启动:
服务提供者:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\main\java\com\credream\
cloud\CredreamserviceSimpleProviderUserApplication.java
然后启动:
服务消费者:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\
cloud\CredreamserviceSimpleProviderUserApplication.java
然后访问一下服务消费者:
看看能不能,消费服务提供者的api
http://localhost:7901/movie/1
{"id":1,"username":"user1","name":"张三","age":20,"balance":100.00}
可以看到没问题,服务消费者已经消费了服务提供者的api了
--------------------------------------
21.好,总结一下
服务提供者:
1.
//2.这里说一下这个注解:
//@GetMapping
//这个其实是一个组合注解
//点进去看看源码:
/* @author Sam Brannen
* @since 4.3
* @see GetMapping
* @see PostMapping
* @see PutMapping
* @see DeleteMapping
* @see RequestMapping
*/
// @Target(ElementType.METHOD)
// @Retention(RetentionPolicy.RUNTIME)
// @Documented
// @RequestMapping(method = RequestMethod.PATCH)
// public @interface PatchMapping {
//可以看到除了:@GetMapping还有PostMapping,PutMapping等
//其实他相当于:
//@RequestMapping(value="/xxx",method=RequestMethod.GET)
//相当于这个
//同样,post也是这样
@GetMapping("/simple/{id}")
----------------------------------
2.yml文件:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src
\main\resources\application.yml
1.注意这个文件是有规则的,有缩进的,没有缩进会报错
server:
port: 7900
spring:
jpa:
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource:
platform: h2
//2.默认这里用schema.sql,data.sql
//当然这个是默认的,不配也是叫这个名字.
//这里可以删除这两个可以试试
//
schema: classpath:schema.sql
data: classpath:data.sql
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
com.itmuch: DEBUG
删除后跑跑:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-user\src\
main\resources\application.yml
server:
port: 7900
spring:
jpa:
generate-ddl: false
show-sql: true
hibernate:
ddl-auto: none
datasource:
platform: h2
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
com.itmuch: DEBUG
可以看到也是可以运行的
-----------------------------------
22.关于服务消费者:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie
\credreamservice-simple-provider-movie\src\main\java
\com\credream\cloud\
CredreamserviceSimpleProviderUserApplication.java
package com.credream.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class CredreamserviceSimpleProviderUserApplication {
//1.这里添加restTemplate方法,注意这个Bean注解,根据引入的类,新建一个对象,
//返回,这里方法的名字,可以随便起,但是应该跟:
//@Autowired controller中的自动装配对应起来
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(CredreamserviceSimpleProviderUserApplication.class, args);
}
}
注意:
@Bean相当于:
private RestTemplate restTemplate=new RestTemplate();
比如:
package com.credream.cloud;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class CredreamserviceSimpleProviderUserApplication {
//2.这里:::
private RestTemplate restTemplate=new RestTemplate();
// //1.这里添加restTemplate方法,注意这个Bean注解,根据引入的类,新建一个对象,
// //返回,这里方法的名字,可以随便起,但是应该跟:
// //@Autowired controller中的自动装配对应起来
// @Bean
// public RestTemplate restTemplate() {
// return new RestTemplate();
// }
public static void main(String[] args) {
SpringApplication.run(CredreamserviceSimpleProviderUserApplication.class, args);
}
}
---------------------------------------
其他的没有什么注意的了.
好,刚才花了一些时间来写了一个小例子,
其实例子有很多问题:
比如1.
在服务消费者中:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud
\controller\MovieController.java
这里:
package com.credream.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.credream.cloud.entity.User;
//1.这里,添加rest注解,生成restful风格api
@RestController
public class MovieController {
//2.自动装配,通过restTemplate获取服务提供者提供的api
@Autowired
private RestTemplate restTemplate;
//3.mapping
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
//1.注意这里:
//第一个问题:
//这里的地址是写死的,硬编码问题,这个在传统的
//系统中可能没问题
//但是在微服务架构中,可能是有问题的
//因为在微服务架构中,服务的ip地址可能会变的
//那怎么办?
return this.restTemplate.getForObject("http://localhost:7900/simple/"+id, User.class);
}
}
------------------------------------------
23.可以这样:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\java\com\credream\cloud\controller
\MovieController.java
这样写:
package com.credream.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.credream.cloud.entity.User;
//1.这里,添加rest注解,生成restful风格api
@RestController
public class MovieController {
//2.自动装配,通过restTemplate获取服务提供者提供的api
@Autowired
private RestTemplate restTemplate;
// @GetMapping("/movie/{id}")
// public User findById(@PathVariable Long id) {
// return this.restTemplate.getForObject("http://localhost:7900/simple/"+id, User.class);
// }
//
//3.采取这种方式,可以摆脱硬编码的问题
@Value("${user.userServicePath}")
private String userServicePath;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject(this.userServicePath + id, User.class);
}
}
-----------------------------
24.把这个地址配置在yml中:
E:\SpringCloudWorkSpace\credreamservice-simple-provider-movie\credreamservice-simple-provider-movie\src\main\
resources\application.yml
spring:
application:
name: microservice-consumer-movie
server:
port: 7901
user:
userServicePath: http://localhost:7900/simple/
这里配置一下
-------------------------
25.好,但是这样也是有问题的
比如,我服务者的ip变了,虽然,消费者的代码不用变了,但是配置文件
yml还是需要变,而这个消费者,又可能是其他微服务的提供者
这样下去就很麻烦维护了
--------------------
因为在大型项目中,可能微服务会有很多,比如上百个,
上万个,因为在亚马逊的首页,就调用了800多个微服务
那这个时候,咱们可以咱们怎么办?
可以在服务的提供者群的终端加入一个nginx做反向代理对吧
画图:微服务架构需要解决的问题服务架构中的地址文件_反向代理.png
movie微服务消费者 | user微服务提供者
| ....微服务提供者
| ....微服务提供者
| ....服务群
|中间做nginx反向代理
|把ip弄成一样的
-------------------------------------------
咱们说一个消费者的,提供者可能有上百个,那么这个消费者,
又可能是其他消费者的提供者,那么又需要做反向代理,
那么这样下去又麻烦了,那么怎么解决
下次再说哈哈哈.....
------------------------------