F1V3.0-16 快速开发一个微服务

来源:互联网 发布:淘宝美工的营销手段 编辑:程序博客网 时间:2024/05/17 02:04

引言

本文介绍了如何快速开发一个F1平台的微服务,面向开发人员,按本文可以快速建成一个微服务最基础的部分。

新建maven项目

F1平台的微服务是maven项目,在eclipse中的创建过程如下。

 

创建一个简单的maven项目跳过archetype选择


 

用f1-parent做父模块

 

点击"finish"完成项目的创建。


编写pom文件


把 f1-starter和spring-boot-starter-web引入到pom文件中

通过搜索找到f1-starter和spring-boot-starter-web,把它们添加为依赖。

然后保存pom.xml

 

如果想要在改了代码后不会每次都重启,用加上spring-boot-devtools依赖,可以热部署

 

编写启动类


微服务要想启动就必须有启动类,启动类创建过程如下:

做一个带main方法的类作为启动类

 

在启动类上加上@SpringBootApplication标注,在main方法中调用SpringApplication的run方法启动当前这个SpringBoot项目

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

如下图启动成功

编写controller


就是普通的springMVC控制器,用来接收前台的请求,把结果返回给前台

@RestController@RequestMapping("/first")public class HelloWorldController {
@ApiOperation(value = "控制器示例", httpMethod = "GET", response = String.class, notes = "控制器示例")@ApiParam(required = false, name = "name", value = "名字")@RequestMapping(value = "", method=RequestMethod.GET)public String hello(String name) {return "你好!"+name;}


 

使用数据库


数据存在数据库中,要想从数据库中存取数据就要配置数据源,具体方法如下:

在application.properties中配置上和数据库的连接信息

 

spring.datasource.url=jdbc:mysql://192.168.***.***:3306/us_sysspring.datasource.username=****spring.datasource.password=****spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContextspring.datasource.type=com.alibaba.druid.pool.DruidDataSource# 下面为连接池的补充设置,应用到上面所有数据源中# 初始化大小,最小,最大spring.datasource.initialSize=5spring.datasource.minIdle=5spring.datasource.maxActive=20# 配置获取连接等待超时的时间spring.datasource.maxWait=60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒spring.datasource.timeBetweenEvictionRunsMillis=60000# 配置一个连接在池中最小生存的时间,单位是毫秒spring.datasource.minEvictableIdleTimeMillis=300000spring.datasource.validationQuery=SELECT1FROMDUALspring.datasource.testWhileIdle=truespring.datasource.testOnBorrow=falsespring.datasource.testOnReturn=false# 打开PSCache,并且指定每个连接上PSCache的大小spring.datasource.poolPreparedStatements=truespring.datasource.maxPoolPreparedStatementPerConnectionSize=20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙spring.datasource.filters=stat,wall,log4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据#spring.datasource.useGlobalDataSourceStat=trueplatform.config.dbtype=mysql

然后创建查询数据库的Service的接口和实现类

public interface HelloWorldService {String queryDb();}

@Service("helloWorldService")@Transactional(value="transactionManager", propagation=Propagation.REQUIRED)public class HelloWorldServiceImpl implements HelloWorldService {@Autowiredprivate GenericDao genericDao;@Overridepublic String queryDb() {List<?> ls = genericDao.getDataWithSQL("select count(1) from us_sys.tb_sys_person");return "人数:"+ls.get(0).toString();}}

最后把service注入到controller中

 

@Autowiredprivate HelloWorldService helloWorldService;@ApiOperation(value = "查询数据库示例", httpMethod = "GET", response = String.class, notes = "查询数据库示例")@ApiParam(required = false, name = "name", value = "名字")@RequestMapping(value = "queryDb", method=RequestMethod.GET)public String queryDb() {String returnstr = helloWorldService.queryDb();return returnstr;}

效果:



注册到eureka


eureka是一个服务器,主管微服务的注册和发现,微服务注册到eureka中才可以互相访问,下边是配置过程:

配置好eureka的地址和是否注册到eureka

在application.properties中加参数

# 注册中心地址eureka.client.serviceUrl.defaultZone=http://192.168.1.20:1111/eureka/eureka.client.registerWithEureka=trueeureka.client.fetchRegistry=true# 客户端在注册时就会使用自己的ip地址而不是主机名(客户端自身加)eureka.instance.preferIpAddress=true

配置好微服务的名字和端口,eureka通过这个发现微服务

# 服务Idspring.application.name=f1-microService1server.port=8080

在启动类上加标注@EnableDiscoveryClient

@EnableDiscoveryClient@SpringBootApplicationpublic class MstApplication {
 

在pom.xml中引入spring-cloud-starter-eureka

 

然后启动微服务,就可以在eureka中看到对应的注册信息


单元测试


测试驱动开发TDD, 都是要先写单元测试,单元测试可以提高代码的质量,下面做一个控制器的单元测试:

创建一个测试类

 

放到test 目录下

 

下边是测试类的代码,用mock方式请求了这个控制器,并对结果进行对比

@SpringBootTest(classes=com.jb.mst.MstApplication.class)@AutoConfigureMockMvcpublic class HelloWorldControllerTest extends TestTemplate {@Testpublic void test() throws Exception {ResultActions result = this.mockMvc.perform(post("/first").param("name", "abcda老王")).andDo(print()).andExpect(status().isOk()).andExpect(content().string(containsString("abcda老王")));}

 

这样就完成了一个对控制器的单元测试,run as junit Test 测试通过了

swagger配置


swagger是微服务的api生成框架,用它可以生成内容丰富详细的控制器接口api, 可以用当前微服务url加swagger-ui.html进行查看,并可以在页面上对接口进行测试,非常方便,下面是具体配置方法:

 

首先引入f1-starter-configure依赖, 上边已经加入了f1-starter就不用加了,已经级联引入了

 

然后给控制器加上swagger的标注

@ApiOperation(value = "控制器示例", httpMethod = "GET", response = String.class, notes = "控制器示例")@ApiParam(required = false, name = "name", value = "名字")@RequestMapping(value = "", method=RequestMethod.GET)public String hello(String name) {return "你好!"+name;}

然后就可以访问swagger查看对应接口的api以及进行测试。


点击Authorize进行登录,然后就可以点击 Try it out进行测试了。





使用统一权限


F1平台的各模块都是以微服务的形式存在的,都需要有权限认证才能访问,我们用一个名叫authServer的微服务作为授权服务器,各微服务都通过授权服务器进行统一权限认证,方便进行权限的管理。给当前微服务加权限的方法如下。

在当前的微服务中依赖f1-starter-auth(如果已经引入了f1-starter,就会间接引入f1-starter-auth),如果没有授权的请求来访问,就会被拒绝。

 

application.properties中加入权限服务器参数:


###########################oauth服务器相关配置###################### 认证服务器凭证security.sessions:neversecurity.oauth2.client.client-id: client-idsecurity.oauth2.client.client-secret: client-secretsecurity.oauth2.client.access-token-uri: http://IP地址/uaa/oauth/token security.oauth2.client.user-authorization-uri: http://IP地址/uaa/oauth/authorize security.oauth2.resource.user-info-uri: http://IP地址/uaa/user
# 断路器配置共享security上下文hystrix.shareSecurityContext: true###########################swagger兼容授权配置#####################security.userOauth.type=oauth2security.userOauth.tokenName=access_tokensecurity.userOauth.scope.code=writesecurity.userOauth.scope.desc=writeapp.key=f1swaggerapp.name=F1平台微服务请求APIapp.desc=更多的下载资源和信息请查看:http://192.168.1.173/f1-platform/f1-microService/ app.version=3.0.0app.termsOfServiceUrl=http://192.168.1.173/f1-platform/f1-microService/ app.contact.name=平台组app.contact.url=http://http://blog.csdn.net/zhbr_f1 app.contact.email=**app.license=The F1 Platform, Version 3.0app.licenseUrl=http://http://blog.csdn.net/zhbr_f1 


加入redis的配置,因为权限认证信息要缓存在redis中

####################### REDIS (RedisProperties)# Redis数据库索引(默认为0spring.redis.database=0# Redis连接密码spring.redis.password=****# Redis数据库服务地址spring.redis.host=192.168.***.***# Redis服务器连接端口spring.redis.port=6379# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1# 连接池中的最大空闲连接spring.redis.pool.max-idle=8# 连接池中的最小空闲连接spring.redis.pool.min-idle=0# 连接超时时间(毫秒)spring.redis.timeout=0


在启动类上加上标注:

 

@EnableOAuth2Sso

这样就只有授权的请求可以访问当前微服务了

在刚才那个url后边加上权限相关的参数(用户名密码认证通过后返回的,真正系统中是自动加上的,这里加到url后边只是为了演示)就可以访问了