SpringBoot +SpringCloud为服服务示例,整合FreeMaker,AngularJS
干货一篇,本节以SpringBoot + SpringCloud为例 构建轻量级微服务,旨在推荐一种更加敏捷的开发流程,本篇暂不会提及相关概念,皆以代码示意.
GIT:https://github.com/poai/spring-cloud-zookeeper-demo.git
关键技术简介:
  • Zookeeeper,分布式协同服务,集群环境中使用的较多,微服务中用来做服务发现,负载均衡,Leader选举等.
  • SpringBoot,敏捷开发框架,集Spring,SpirngMVC等Spring体系内技术于一体,基于IOC容器进行资源整合,屏蔽了开发,部署应用程序的复杂性.
  • SpringCloud,云环境的产物,致力于解决分布式解决方案集成,与SpringCloud无缝整合.
Server端实现:
  • POM依赖

<dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
			<version>1.0.2.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-feign -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-netflix</artifactId>
				<version>1.2.5.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

  • SpringBoot 核心配置文件 application.yml

server:
  port: 9997
spring:
  application:
    #服务名称,CLIENT端用来享受服务
    name: USERSERVER
  cloud:
    zookeeper:
      #ZK_ADDRESS
      connect-string: host219:2181,host223:2181,host224:2181
      discovery:
        register: true
        #服务地址
        instance-host: 10.150.27.29
        #服务端口
        instance-port: ${server.port}
        enabled: true
    

  • server端应用程序入口函数ZkServerApplication.java
@SpringBootApplication
@RestController
//服务注册到ZK
@EnableDiscoveryClient
public class ZkServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(ZkServerApplication.class, args);
	}
}
  • server端 RESTFULL 接口示例

public class Bean {
	private String name;
	private String likes;
	private String id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getLikes() {
		return likes;
	}

	public void setLikes(String likes) {
		this.likes = likes;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

}
@RestController
public class UserService {
	// PathVariable
	@RequestMapping("/user/{id}")
	public Bean getUserInfo(@PathVariable("id") String id) {
		Bean bean = new Bean();
		bean.setLikes("Orange");
		bean.setName("lili");
		bean.setId(id);
		return bean;
	}
	// Path
	@RequestMapping
	public Bean getUserList(@RequestParam(required = true, value = "id") String id) {
		Bean bean = new Bean();
		bean.setLikes("Banana");
		bean.setName("Mr Wang");
		bean.setId(id);
		return bean;
	}
}

Server端总结:每启动一个Server端实例SpringCloud向ZK以"USERSERVER"为服务唯一标识在ZK "/services"节点下以该服务标识为路径注册服务,该特性由"@EnableDiscoveryClient" 注解及application.yml中相关配置进行驱动.



Client端实现

  • POM依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<!-- FEGIN:REST CLIENT -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-feign</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-ribbon -->
	<!-- RIBBON:客户端负载均衡器 -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-ribbon</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
	<!-- HYSTRIX:断路器 -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-hystrix</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zookeeper-discovery -->
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
		<version>1.0.2.RELEASE</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-freemarker</artifactId>
	</dependency>
	<!-- 热部署包 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/oracle/ojdbc14 -->
	<!-- https://mvnrepository.com/artifact/oracle/ojdbc14 -->
	<dependency>
		<groupId>oracle</groupId>
		<artifactId>ojdbc14</artifactId>
		<version>10.2.0.1.0</version>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-configuration-processor</artifactId>
		<optional>true</optional>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
	</dependency>

</dependencies>


  • SpringBoot 核心配置文件 application.yml

server:
  port: 9990
spring:
  application:
    name: USERCLIENT
  cloud:
    zookeeper:
      enabled: true
      connect-string: host219:2181,host223:2181,host224:2181
      discovery:
        root: /services
        register: true
  datasource:
    url: jdbc:oracle:thin:@host233:1521/orcl
    username: root
    password: root
    driver-class-name : oracle.jdbc.driver.OracleDriver


  • client端主函数实现,ZkClientApplication.java

@SpringBootApplication
// 启用REST 客户端
@EnableFeignClients
// 启用客户端负载均衡
@RibbonClient(name = "my", configuration = RibbonConfig.class)
// 启用服务发现
@EnableDiscoveryClient
// 启用断路器
@EnableHystrix
@ImportResource(value = "spring_mvc.xml")
@ComponentScan("cn.com.xiaofen")
public class ZkClientApplication {
	public static void main(String[] args) {
		SpringApplication.run(ZkClientApplication.class, args);
	}
	/* Spring JDBC */
	@Bean
	public JdbcTemplate primaryJdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	/* TOMCAT DataSourcePool */
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}
}

  • client消费指定server控制器即service实现,主函数中使用@EnableDiscoveryClient注解驱动服务自动发现,使用@RibbonClient注解驱动客户端负载均衡器,使用@EnableFeignClients注解驱动以REST CLIENT注解形式进行RPC调用,@FeignClient 指向一个经过客户端负载均衡后选择的Service连接并消费服务,服务接口的实例化由Spring框架实现并完成自动装配.

@RestController
public class UserController {

	@Autowired
	private UserService us;

	@RequestMapping("/user/{id}")
	public String getUserInfo(@PathVariable("id") String id) {
		return us.getUserInfo(id);
	}
	@RequestMapping("/user")
	public String getUSerList(@RequestParam("id") String id) {
		return us.getUSerList(id);
	}
}
@FeignClient("USERSERVER")
public interface UserService {
	@RequestMapping("/user/{id}")
	public String getUserInfo(@PathVariable("id") String id);
	@RequestMapping("/user")
	public String getUSerList(@RequestParam("id") String id);
}

  • 配置数据源,推荐使用Tomcat内置数据源,配置属性见application.yml ,数据源创建并注入IOC过程见ZkClientApplication.java 主函数,有注释,DAO层可以使用JdbcTemplate 获取其它开源框架如Mybatis,Hibernate等.
  • 与FreeMaker整合,SpringBoot中不推荐使用JSP,JSP带来的劣势在于项目不能以独立jar的形式发布,这里一FreeMaker为例,只需要添加SpringBoot FreeMaker的依赖即可. 见POM依赖.
Controller

@Controller
public class ByonetController {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@RequestMapping("/byonetListFreeMaker")
	public String byonetListFreeMaker(Map<String,Object> model) {
		String sql = "select kkid,kkmc,x,y from t_itgs_tgsinfo";
		BeanPropertyRowMapper<Byonet> rowMapper = new BeanPropertyRowMapper<Byonet>(Byonet.class);
		List<Byonet> byonets=jdbcTemplate.query(sql, rowMapper);
		model.put("byonets", byonets);
		return "byonetList";
	}
}

FreeMaker模版,路径src/main/resources/remplates/byonetList.ftl

<html>
<head>
  <title>卡点列表</title>
</head>
<body>
  <p>Our latest product:
  
  <table>
  	<tr>
  		<th>KKID</th>
  		<th>KKMC</th>
  		<th>X</th>
  		<th>Y</th>
  	</tr>
  	<#list byonets as byonet>
  		<tr>
  			<td>${byonet.kkid}</td>
  			<td>${byonet.kkmc}</td>
  			<td>${ (byonet.x)! }</td>
  			<td>${ (byonet.y)!}</td>
  		</tr>
  	</#list>
  </table>
</body>
</html>


  • AngularJS尝鲜,

controller

@RestController
public class ByonetControllerRest {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping("/byonetList")
	public List<Byonet> byonetList() {
		String sql = "select kkid,kkmc,x,y from t_itgs_tgsinfo";
		BeanPropertyRowMapper<Byonet> rowMapper = new BeanPropertyRowMapper<Byonet>(Byonet.class);
		return jdbcTemplate.query(sql, rowMapper);
	}
	
	@RequestMapping("/byonetList/{kkid}")
	public List<Byonet> byonetListById(@PathVariable(required=true,name="kkid")String kkid) {
		String sql = "select kkid,kkmc,x,y from t_itgs_tgsinfo where kkid=?";
		BeanPropertyRowMapper<Byonet> rowMapper = new BeanPropertyRowMapper<Byonet>(Byonet.class);
		return jdbcTemplate.query(sql, rowMapper,kkid);
	}
}

index.html ,下例以请求REST SERVER获取JSON集合填充一个表格为例,此外推荐学习VUE.JS

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script
	src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
	<h1>RPC测试</h1>
	<a href="http://it:9990/byonetListFreeMaker" id="info">info_1</a>
	<br>
	<a href="http://it:9990/homePage" id="list">info_2</a>
	<br>
	<h1>FreeMaker测试</h1>
	<a href="http://it:9990/byonetListFreeMaker" id="info">/byonetListFreeMaker</a>
	<br>
	<a href="http://it:9990/homePage" id="list">/homePage</a>
	<hr>
	<hr>
	<h1>AngularJS 测试</h1>
	<div ng-app="myApp" ng-controller="customersCtrl">
		<table>
			<tr>
				<td>ID</td>
				<td>NAME</td>
				<td>X</td>
				<td>Y</td>
				<td>HAND</td>
			</tr>
			<tr ng-repeat="x in names">
				<td><a href="">{{ x.kkid }}</a></td>
				<td>{{ x.kkmc }}</td>
				<td>{{ x.x }}</td>
				<td>{{ x.y }}</td>
				<td><a href="">info</a></td>
			</tr>
		</table>
		<script>
			var app = angular.module('myApp', []);
			app.controller('customersCtrl', function($scope, $http) {
				$http.get("/byonetList").success(function(response) {
					$scope.names = response;
				});
			});
		</script>
</body>
</html>





Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐