1. 程式人生 > >SpringCloud之Feign

SpringCloud之Feign

Feign實踐

在上一篇的基礎上,新建一個Feign的maven子專案,專案結構

①FeignController

package com.yj.feign.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.yj.feign.service.FeignService;

@RestController
public class FeignController {

	@Autowired
	private FeignService feignService;

	@GetMapping(value = "/hiFeign")
	public String hiFeign(@RequestParam String name) {
		return feignService.hiFeign(name);
	}
}

②FeignService

package com.yj.feign.service;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "eureka-client")
public interface FeignService {
	@RequestMapping(value = "/hiEureka", method = RequestMethod.GET)
	String hiFeign(@RequestParam(value = "name") String name);
}

③FeignApplication

package com.yj.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class FeignApplication 
{
	public static void main(String[] args) {
		SpringApplication.run(FeignApplication.class, args);
	}
}

④application.properties

server.port=8006

spring.application.name=feign
eureka.client.serviceUrl.defaultZone=http://admin:[email protected]:8001/eureka,http://admin:[email protected]:8002/eureka
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
eureka.instance.hostname=${spring.cloud.client.ipAddress}

⑤logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />

    <!-- 彩色日誌格式 -->
    <property name="CONSOLE_LOG_PATTERN"
              value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />

    <!-- 控制檯列印日誌的相關配置 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}<!--%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%class:%line] - %m%n--></pattern>
            <charset>utf8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debug</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
    </appender>

    <!-- 檔案儲存日誌的相關配置 -->
    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/Feign.log</file>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}<!--%d{yyyy-MM-dd HH:mm:ss.SSS} [%level] [%class:%line] - %m%n--></pattern>
            <charset>utf8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>ACCEPT</onMismatch>
        </filter>
        <!-- 迴圈政策:基於時間建立日誌檔案 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>logs/%d{yyyy-MM-dd}/Feign.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
        </rollingPolicy>
    </appender>

    <logger name="com.yj.eureka" level="DEBUG" />
    <!-- 基於dubug處理日誌:具體控制檯或者檔案對日誌級別的處理還要看所在appender配置的filter,如果沒有配置filter,則使用root配置 -->
    <root level="info">
        <appender-ref ref="console" />
        <appender-ref ref="file" />
    </root>
</configuration>

⑥pom.xml

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.yj</groupId>
		<artifactId>SpringCloud</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>

	<artifactId>Feign</artifactId>
	<name>Feign</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

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

	<build>
		<finalName>${artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>

					<archive>
						<manifest>
							<mainClass>com.yj.feign.FeignApplication</mainClass>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib</classpathPrefix>
						</manifest>
						<manifestEntries>
							<Class-Path>./</Class-Path>
						</manifestEntries>
					</archive>
					<excludes>
						<exclude>config/**</exclude>
						<exclude>**.xml</exclude>
						<exclude>**.properties</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<appendAssemblyId>false</appendAssemblyId>
					<descriptors>
						<descriptor>src/main/build/package.xml</descriptor>
					</descriptors>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
		<testResources>
			<testResource>
				<directory>src/main/resources</directory>
			</testResource>
		</testResources>
	</build>
</project>

⑦start.sh,stop.sh

#! /bin/bash

moduleName="Feign"

pidPath="./$moduleName-tpid"

rm -f $pidPath

java -jar ./$moduleName.jar &

echo $!>$pidPath
#! /bin/bash

moduleName="Feign"

tpid=`cat ./$moduleName-tpid | awk '{print $1}'`

tpid=`ps -aef | grep $tpid | grep -v grep | grep $moduleName |awk '{print $2}' `

if [ ${tpid} ];then
	kill -9 $tpid
fi

⑧package.xml

<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3
          http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>package</id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>true</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>bin</directory>
            <outputDirectory>/</outputDirectory>
        </fileSet>
        <fileSet>
            <directory>src/main/resources</directory>
            <outputDirectory>/</outputDirectory>
            <excludes>
                <exclude>mapper/**</exclude>
            </excludes>
        </fileSet>
        <fileSet>
            <directory>${project.build.directory}</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>${artifactId}.jar</include>
            </includes>
        </fileSet>
    </fileSets>
    <dependencySets>
        <dependencySet>
            <outputDirectory>lib</outputDirectory>
            <scope>runtime</scope>
            <excludes>
                <exclude>${groupId}:${artifactId}</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
</assembly>

⑨部署啟動,Feign專案也被註冊到Eureka上面了