项目中需要使用到这个 所以学习了下
案例下载地址:https://download.csdn.net/download/qq_39477018/12458734
1.创建Eureka注册中心
注意spingboot2.X和l.5X使用的版本不一样 需要了解的可以自行百度,下面给出2.X的配置信息,以及1.5X的配置
2.X:
新建一个springboot项目 加入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">
<modelVersion>4.0.0</modelVersion>
<groupId>witsky-eureka</groupId>
<artifactId>witsky-eureka</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.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>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置application配置文件
spring.application.name=spring-cloud-eureka
#false表示它不会自己像自己注册,
eureka.client.register-with-eureka=false
#为客户端是否获取eureka服务器注册表上的注册信息,默认为true,由于我们是本来就是编写eureka server,所以这里设置为flase不然启动会报错
eureka.client.fetch-registry=false
#为Eureka的注册地址
eureka.client.serviceUrl.defaultZone=http://192.168.150.131:10230/eureka/
debug=false
在sprigboot的启动类上加上注解@EnableEurekaServer,表明是Eureka的服务
@SpringBootApplication
@EnableEurekaServer
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后启动 访问localhost 可以查看到以下界面,画框的部分说明还没有服务注册进来
2.编写服务提供者(也就是需要写的业务逻辑的项目)
新建一个springboot 加上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">
<modelVersion>4.0.0</modelVersion>
<groupId>witsky-eureka-client</groupId>
<artifactId>witsky-eureka-client</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.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>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- Eureka客户端启动需要依赖web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置application配置文件
# http port
server.port=10228
#server.address=192.168.110.105
# 项目contextPath
server.servlet.context-path=/rcsmediamanage
# 错误页,指定发生错误时,跳转的URL。请查看BasicErrorController源码便知
server.error.path=/error
witsky.ip=87
# 使用ip地址注册(否则使用主机名)
eureka.instance.prefer-ip-address=true
# 有多个ip地址时设置优先使用的地址表达式
#spring.cloud.inetutils.preferred-networks=^192
# 注册中心地址
eureka.client.service-url.defaultZone=http://127.0.0.1:10226/eureka
spring.application.name=eureka-client
#eureka微服务实例名称修改
#eureka.instance.instance-id=192.168.150.131:${server.port}:${spring.application.instance_id:${random.int[0,20]}}
eureka.instance.instance-id=87:${server.port}
#eureka.client.healthcheck.enabled=true
logging.path=proglog
debug=false
在启动类上加上注解@EnableEurekaClient 并编写一个controller,我的为了方便直接写在启动类里面在
@SpringBootApplication
@EnableEurekaClient
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Value("${witsky.ip}")
private String ip;
@RequestMapping(method= RequestMethod.GET, value = "/persons/{id}")
public String getById(@PathVariable("id") int id){
System.out.println("===我是服务端啊");
return ip+":Hello==="+id+", boby do you love me";
}
@RequestMapping(method= RequestMethod.POST, value = "/persons")
public String add(@RequestBody Map<String, Object> map){
return ip+":Hello==="+map.toString();
}
}
然后启动 可以查看微服务控制面有了一个注册
3.创建一个服务提供者接口暴露的服务(使用的是feign,有用ribbon的请另行百度啦)
新建一个springboot项目加入相关的依赖
<?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>witsky-eureka-feign</groupId>
<artifactId>witsky-eureka-feign</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.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>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置配置文件
# http port
server.port=10225
#server.address=192.168.110.105
# 项目contextPath
#server.servlet.context-path=/rcsmaapapi
# 错误页,指定发生错误时,跳转的URL。请查看BasicErrorController源码便知
server.error.path=/error
# 使用ip地址注册(否则使用主机名)
eureka.instance.prefer-ip-address=true
# 有多个ip地址时设置优先使用的地址表达式
#spring.cloud.inetutils.preferred-networks=^192
# 注册中心地址
eureka.client.service-url.defaultZone=http://127.0.0.1:10226/eureka,http://192.168.150.133:10230/eureka
spring.application.name=feign-client
eureka.instance.instance-id=87:${server.port}
#eureka.client.healthcheck.enabled=true
# Feign支持请求响应GZIP压缩:
feign.compression.request.enabled=true
feign.compression.response.enabled=true
# 把普通的 HTTPURLConnection 替换为使用 HTTPClient
feign.httpclient.enabled=true
feign.httpclient.max-connections=100
feign.httpclient.max-connections-per-route=50
#支持压缩的mime types
feign.compression.request.mime-types=application/xml,application/json
feign.compression.request.min-request-size=1024
# 日志支持
logging.level.project.user.UserClient: DEBUG
logging.path=proglog
debug=false
在启动类上加入注解@EnableEurekaClient
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
创建feign接口。@FeignClient中的name表示服务提供者(也就是第二个项目配置文件配置的那个eureka-client)的名称。注意这里不能用@GetMapping和@PostMapping等,不然会报错。
package cn.witsky.main.feignservice;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
//@FeignClient 注解, 注解中的参数为调用Eureka中的服务的名称(ID)
//value 指的是服务端application中的spring.application.name=eureka-client
//path 指的是服务端application中的server.servlet.context-path=/rcsmediamanage
@FeignClient(value = "eureka-client",path ="/rcsmediamanage") //请求Eureka中的服务中goods服务
@Service
public interface EurekaService {
@RequestMapping(method= RequestMethod.GET, value = "/persons/{id}")
String getPerson(@PathVariable("id") int id);
@PostMapping("/persons")
String createPerson(@RequestBody Map<String, Object> map);
}
然后创建一个controller
package cn.witsky.main;
import cn.witsky.main.feignservice.EurekaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WorkController {
@Autowired
private EurekaService eurekaService;
@RequestMapping(value = "/getById/{id}", method = RequestMethod.GET)
public String test(@PathVariable("id") int id){
return eurekaService.getPerson(id);
}
}
启动项目 观察微服务页面两个服务已经注册进去啦
然后访问暴露接口的服务:
ps: 服务的提供者可以在好几台上部署,可以实现负载均衡。注意端口要改一下,但是服务名称不可更改,因为暴露的接口中引用的有指定的服务名称。
1.5X配置
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">
<modelVersion>4.0.0</modelVersion>
<groupId>rcs-mediamanage-eureka</groupId>
<artifactId>rcs-mediamanage-eureka</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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-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>
配置文件
# http port
server.port=8800
server.address=0.0.0.0
server.error.path=/error
#####eureka
spring.application.name=spring-cloud-eureka
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://192.168.150.131:10230/eureka
# log
logging.path=proglog/mediamanageeureka
debug=false
启动类:
服务的提供程序: ps(我是把服务的提供者和暴露接口的写在一个项目中了 这个1.5x使用的暴露接口的是ribbon)
新建项目 pomyil
<?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>rcs-mediamanage</groupId>
<artifactId>rcs-mediamanage</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.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>
<!--<spring-cloud.version>Greenwich.SR2</spring-cloud.version>-->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<!--druid 连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis 持久框架-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<!--optional我没弄明白,都说必须为true,但我测试true,false,不加都可以-->
<optional>true</optional>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!--eureka-->
<!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
</dependencies>
<!--eureka-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 没有该配置,devtools 不生效 -->
<fork>true</fork>
<addResources>true</addResources>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<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>
<compilerArgs>
<arg>-XDignore.symbol.file</arg>
</compilerArgs>
<fork>true</fork>
<!-- <compilerArguments>-->
<!-- <bootclasspath>${JAVA_HOME}/jre/lib/rt.jar;${JAVA_HOME}/jre/lib/jce.jar</bootclasspath>-->
<!-- </compilerArguments>-->
</configuration>
</plugin>
</plugins>
</build>
</project>
配置文件:
# http port
server.port=8801
#server.address=192.168.110.105
# 项目contextPath
server.context-path=/rcsmediamanage
# 错误页,指定发生错误时,跳转的URL。请查看BasicErrorController源码便知
server.error.path=/error
######eureka配置
witsky.ip=87
# 使用ip地址注册(否则使用主机名)
eureka.instance.prefer-ip-address=true
# 有多个ip地址时设置优先使用的地址表达式
#spring.cloud.inetutils.preferred-networks=^192
# 注册中心地址
eureka.client.service-url.defaultZone=http://192.168.150.131:10230/eureka
#服务名称(不可随意更改)
spring.application.name=media-service
#eureka微服务实例名称修改
#eureka.instance.instance-id=192.168.150.131:${server.port}:${spring.application.instance_id:${random.int[0,20]}}
eureka.instance.instance-id=87:${server.port}
启动类
package cn.witsky.rcsmediamanage;
import cn.witsky.rcsmediamanage.utils.CustomErrorHandler;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@EnableAsync
@Configuration
@EnableCaching
@EnableScheduling
@EnableEurekaClient
@EnableDiscoveryClient
public class Application {
@Autowired
public Config config;
@LoadBalanced
@Bean(name = "restTemplate")
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(20000);
factory.setConnectTimeout(3000);
RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(new CustomErrorHandler());
// 找出并修改默认的StringHttpMessageConverter
// 关闭Accept-Charset的输出(防止输出超长的编码列表)
// 设置默认编码为UTF-8
boolean stringConverterFound = false;
for (HttpMessageConverter httpMessageConverter : restTemplate.getMessageConverters()) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter)httpMessageConverter;
stringHttpMessageConverter.setWriteAcceptCharset(false);
stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverterFound = true;
break;
}
}
if (!stringConverterFound) {
// 如果不存在StringHttpMessageC onverter,则创建一个
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
stringHttpMessageConverter.setWriteAcceptCharset(false);
restTemplate.getMessageConverters().add(stringHttpMessageConverter);
}
return restTemplate;
}
@Bean(name = "httpsRestTemplate")
public static RestTemplate httpsRestTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
// RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
restTemplate.setErrorHandler(new CustomErrorHandler());
// 找出并修改默认的StringHttpMessageConverter
// 关闭Accept-Charset的输出(防止输出超长的编码列表)
// 设置默认编码为UTF-8
boolean stringConverterFound = false;
for (HttpMessageConverter httpMessageConverter : restTemplate.getMessageConverters()) {
if (httpMessageConverter instanceof StringHttpMessageConverter) {
StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter)httpMessageConverter;
stringHttpMessageConverter.setWriteAcceptCharset(false);
stringHttpMessageConverter.setDefaultCharset(Charset.forName("UTF-8"));
stringConverterFound = true;
break;
}
}
if (!stringConverterFound) {
// 如果不存在StringHttpMessageC onverter,则创建一个
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
stringHttpMessageConverter.setWriteAcceptCharset(false);
restTemplate.getMessageConverters().add(stringHttpMessageConverter);
}
return restTemplate;
}
// 创建用于重试的retryTemplate
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setBackOffPolicy(new ExponentialBackOffPolicy());
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(3);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(Application.class);
springApplication.run(args);
}
}
使用ribbon 必须要使用 RestTemplate 并且加上注解@LoadBalanced 来请求eureka其他服务的接口
我其他的一个微服务有一个接口
使用方法
@Resource(name = "restTemplate")
private RestTemplate restTemplateHttp;//声明RestTemplate
public void checkFileExpTime() {
ResponseEntity<String> responseEntity= restTemplateHttp.exchange("http://media-service2/rcsmediamanage/persons/15", HttpMethod.GET,null, String.class);
System.out.println("========");}
media-service2 是我刚刚那个getById 项目的服务名称
RestTemplate 可以直接用服务名称就可以请求到其他的微服务
有不懂得可以给我留言叭, 写的比较粗略..