欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springCloud微服务初探

程序员文章站 2024-03-20 22:19:04
...

1.父项目POM文件

<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.lantian</groupId>
  <artifactId>lantian</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>

  <name>lantian</name>
  <url>http://maven.apache.org</url>

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

  <parent>
    <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.5.10.RELEASE</version>
  </parent>

  <modules>
    <module>springCloud-eureka-server</module>
    <module>springCloud-eureka-client</module>
    <module>lantian-eureka</module>
    <module>lantian-gateway</module>
    <module>lantian-upload</module>
    
  </modules>

  <dependencyManagement> 
    <dependencies> 
      <dependency> 
        <groupId>org.springframework.cloud</groupId> 
          <artifactId>spring-cloud-dependencies</artifactId> 
          <version>Dalston.SR3</version> 
          <type>pom</type>  
          <scope>import</scope> 
      </dependency> 
    </dependencies> 
  </dependencyManagement> 

  <dependencies> 
    <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-starter-config</artifactId> 
    </dependency> 

    <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-starter-eureka</artifactId> 
    </dependency> 

    <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-devtools</artifactId> 
      <optional>true</optional> 
    </dependency>

    <dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
	  <groupId>mysql</groupId>
	  <artifactId>mysql-connector-java</artifactId>
	  <scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
    <dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>1.3.1</version>
	</dependency>
    <dependency>  
		<groupId>cglib</groupId>  
		<artifactId>cglib</artifactId>  
		<version>3.2.4</version>  
	</dependency>
	<!-- json jar包 -->
	<dependency>
		<groupId>net.sf.json-lib</groupId>
		<artifactId>json-lib</artifactId>
		<version>2.4</version>
		<classifier>jdk15</classifier>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aop</artifactId>
		<version>4.3.13.RELEASE</version>
	</dependency>

	<!--  AOP  -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-aop</artifactId>
		<version>1.5.9.RELEASE</version>
	</dependency>

  </dependencies>

</project>

2.注册中心eureka
   子项目POM文件

<?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.lantian</groupId>
    <artifactId>lantian</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.lantian</groupId>
  <artifactId>lantian-eureka</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lantian-eureka</name>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
  </dependencies>

  <!-- jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <fork>true</fork>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

    application.properties

server.port=7070
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
eureka.client.registerWithEureka=false
eureka.client.fetchRegistry=false

#
logging.file=/usr/local/lantian/log/eureka.log

    启动类App.java

package com.lantian.eureka;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableEurekaServer
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

3.API网关
   子项目POM文件

<?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.lantian</groupId>
    <artifactId>lantian</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.lantian</groupId>
  <artifactId>lantian-gateway</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lantian-gateway</name>
  <packaging>jar</packaging>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>
  </dependencies>

  <!-- jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <fork>true</fork>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

    application.properties

spring.application.name=zuul

server.port=8080
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:7070/eureka/
zuul.ignored-services="*"
zuul.prefix=/api
zuul.routes.upload.path=/upload/**
zuul.routes.upload.service-id=upload
#转发客户端的header,可以保持session
zuul.routes.upload.sensitiveHeaders="*"

# timeout config
zuul.host.socket-timeout-millis=180000
zuul.host.connect-timeout-millis=180000
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=180000
ribbon.ReadTimeout=180000
ribbon.ConnectTimeout=180000

#
logging.file=/usr/local/lantian/log/gateway.log

    启动类ZuulApplication.java

package com.lantian.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableEurekaClient
@EnableZuulProxy
@EnableDiscoveryClient
public class ZuulApplication {

	public static void main(String[] args) {
		SpringApplication.run(ZuulApplication.class, args);
	}
}

    如果需要跨域的话,根据实际情况设定跨域配置GateWayCorsConfig.java

package com.lantian.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Component
@Configuration
public class GateWayCorsConfig
{
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

4.微服务upload
   子项目POM文件

<?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.lantian</groupId>
    <artifactId>lantian</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.lantian</groupId>
  <artifactId>lantian-upload</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>lantian-upload</name>
  <packaging>jar</packaging>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3</version>
    </dependency>
  </dependencies>

  <!-- jar -->
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <fork>true</fork>
        </configuration>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>src/main/java</directory>
          <includes>
            <include>**/*.xml</include>
          </includes>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>
  </build>
</project>

    application.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml

server.port=8082
eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:7070/eureka/
spring.application.name=upload
#上传文件大小限制
spring.http.multipart.maxFileSize=10MB

#开发、测试、发布的配置文件分开,当前**发布的配置文件
spring.profiles.active=prod

application-prod.properties

spring.datasource.url=jdbc:mysql://localhost:3306/testDb?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=dbuser
spring.datasource.password=dbpass

logging.file=/usr/local/lantian/log/${spring.application.name}.log

newRA.folder.upload=/usr/local/lantian/file/upload

    启动类App.java

package com.lantian.upload;

import javax.sql.DataSource;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@EnableAsync(proxyTargetClass = true)
@MapperScan("com.lantian.mapper")
@EnableDiscoveryClient
public class App {

    @Bean
    @ConditionalOnMissingBean
    public PlatformTransactionManager txManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    public static void main( String[] args ) {
           SpringApplication.run(App.class, args);
    }
}

    服务入口HelloController.java

package com.lantian.upload.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

	@RequestMapping("/test/hello/{info}")
	public String hello(@PathVariable(value="info") String info) {
		return "hello " + info + ", I'm a api from 'upload' service.";
	}
}

5.访问
   先后启动注册中心、网关API和微服务upload
   直接访问微服务upload : http://localhost:8082/test/hello/yourname
   通过网关API访问微服务upload:http://localhost:8080/api/upload/test/hello/yourname

   如果通过网关API访问微服务upload需要上传文件的话,为了文件名不出现乱码,必须用下面的url访问:
   http://localhost:8080/zuul/api/upload/test/uploadapi
   /test/uploadapi为Controller的上传文件api的访问路径