1、Spring Cloud簡介:spring
Spring Cloud是對Netflix的多個開源組件進一步的封裝而成,同時又實現了和雲端平臺,和SpringBoot開發框架很好的集成。 Spring Cloud爲開發者提供了在分佈式系統(配置管理,服務發現,熔斷,路由,微代理,控制總線,一次性token,全居瑣,leader選舉,分佈式session,集羣狀態)中快速構建的工具,使用SpringCloud的開發者能夠快速的啓動服務或構建應用、同時可以快速和雲平臺資源進行對接。
2、建立服務端session
參考Spring Inuti搭建Spring Boot項目 搭建基礎Boot項目app
在pom.xml中添加依賴:框架
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies>
在Application啓動文件中添加註解:@EnableEurekaServer分佈式
@EnableEurekaServer @SpringBootApplication public class SpringCloudApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudApplication.class, args); } }
在配置文件application.properties中添加配置:工具
server.port=1228 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/Eureka/
點擊啓動程序 啓動工程後,訪問:http://localhost:1228/ (注意要有最後的反斜槓) fetch
3、建立提供服務的客戶端代理
參考Spring Inuti搭建Spring Boot項目 搭建基礎Boot項目code
在pom.xml中添加依賴:server
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies>
實現接口提供API支持
/** * Created by 從小就壞 on 2016/12/28. */ @RestController public class HelenController { private final Logger logger = Logger.getLogger(getClass()); @Autowired private DiscoveryClient client; @RequestMapping(value = "/add" ,method = RequestMethod.GET) public String add() { ServiceInstance instance = client.getLocalServiceInstance(); logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r); return "HELEN"; } }
在Application啓動文件中添加註解:@EnableEurekaServer
@EnableEurekaServer @SpringBootApplication public class SpringCloudApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudApplication.class, args); } }
在配置文件application.properties中添加配置:
spring.application.name=compute-service server.port=1229 eureka.client.serviceUrl.defaultZone=http://localhost:1228/eureka/
啓動2個工程你會發現你的服務註冊好了