上一节讲解了,父项目的搭建和服务管制中心子项目的搭建,能够正常启动我们的服务管制中心,现在来看一下我的服务提供者子项目:
(2)服务提供者(Application-Service)
pom文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>mymall-master</groupId>
<artifactId>mymall-master</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>account-service</groupId>
<artifactId>account-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 添加mysql驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- 添加hibernate依赖包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
<!-- 内部其它组件依赖 -->
<dependency>
<groupId>commom-moudle</groupId>
<artifactId>common-moudle</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<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>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
服务启动类ApplicationAppService.class:
package com.account.applicationApp;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
@EnableDiscoveryClient
@SpringBootApplication
@ComponentScan(basePackages = "com.account")//默认情况下,Application只能和API在同一个包下面,如果不在同一个包,必须设置此注解
public class AccountAppService {
public static void main(String[] args){
new SpringApplicationBuilder(AccountAppService.class).web(true).run(args);
}
}
AccountController类,提供给消费者调用的rest接口:
package com.account.controller;
import com.account.config.AccountReturnCode;
import com.account.service.IAccountService;
import com.common.constant.RestApiResult;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
@RestController
@RequestMapping("/acc")
public class AccountController {
private final static Logger log = Logger.getLogger(AccountController.class.getName());
@Autowired
private IAccountService iAccountService;
/**
* 用户注册
*/
@RequestMapping(value="/signup",method = RequestMethod.GET)
public String signUp(@RequestParam String phone, @RequestParam String password){
AccountReturnCode result = iAccountService.signUp(phone,password);
RestApiResult restApiResult = new RestApiResult(result.isSuccess(),result.getCode(),result.getMessage());
return new Gson().toJson(restApiResult);
}
/**
* 用户登录
*/
@RequestMapping(value="login",method = {RequestMethod.GET,RequestMethod.POST})
public String login(@RequestParam String phone,String password){
AccountReturnCode result = iAccountService.login(phone,password);
RestApiResult restApiResult = new RestApiResult(result.isSuccess(),result.getCode(),result.getMessage(),result.getAddmessage());
return new Gson().toJson(restApiResult);
}
}
RestApiResult 是一个公共模块中定义的统一返回给前端的类模板,后续节给出......
@Autowired private IAccountService iAccountService; 提供服务的接口,有具体的实现类,此处直接进行注册依赖bean了~~
package com.account.service;
import com.account.config.AccountReturnCode;
public interface IAccountService {
public AccountReturnCode signUp(String phone, String password);
public AccountReturnCode login(String phone,String password);
}
具体服务实现类:
package com.account.service.impl;
import com.account.config.AccountReturnCode;
import com.account.db.dao.AccountDao;
import com.account.db.entity.AccountEntity;
import com.account.service.IAccountService;
import com.common.constant.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service("AccountServiceImpl")
public class AccountServiceImpl implements IAccountService{
@Autowired
AccountDao accountDao;
@Override
public AccountReturnCode signUp(String phone, String password) {
AccountEntity accountEntity = accountDao.getAccountByPhone(phone);
if (accountEntity != null){
System.out.println("用户已经存在~");
return new AccountReturnCode(false,ReturnCode.INVALID_VALUE,"The user is aready exist.");
}
accountEntity = new AccountEntity();
accountEntity.setUser_id(UUID.randomUUID().toString());
accountEntity.setUser_phone(phone);
accountEntity.setUser_password(password);
boolean result = accountDao.saveAccount(accountEntity);//存储成功和失败的标识码
if (result) {
return new AccountReturnCode(true, ReturnCode.OPER_SUCCESS, "Regist user succeed.");
}
return new AccountReturnCode(false,ReturnCode.OPER_FAILD,"Regist user falied.");
}
@Override
public AccountReturnCode login(String phone, String password) {
AccountEntity accountEntity = accountDao.getAccountByPhoneAndPassword(phone,password);
if (accountEntity != null){
return new AccountReturnCode(true,ReturnCode.OPER_SUCCESS,"",accountEntity.getUser_id());
}
return new AccountReturnCode(false,ReturnCode.NOT_FOUND_RECORD,"The phone or password are not correct");
}
}
看下db包下面的类,包括entity和dao类:
package com.account.db.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="account_tb")
public class AccountEntity {
private String user_id;
private String user_phone;
private String user_password;
@Id
@Column(name="user_id")
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id){
this.user_id = user_id;
}
@Column(name="user_phone")
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
@Column(name="user_password")
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
package com.account.db.dao;
import com.account.db.entity.AccountEntity;
public interface AccountDao {
public AccountEntity getAccountByPhone(String phone);
public AccountEntity getAccountByPhoneAndPassword(String phone,String password);
public boolean saveAccount(AccountEntity accountEntity);
}
package com.account.db.dao.impl;
import com.account.config.SqlSessionFactoryConfig;
import com.account.db.dao.AccountDao;
import com.account.db.entity.AccountEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("AccountDaoImpl")
public class AccountDaoImpl implements AccountDao {
@Override
public AccountEntity getAccountByPhone(String phone) {
SessionFactory sessionFactory = SqlSessionFactoryConfig.getInstance();
Session session = sessionFactory.openSession();
try {
String hql = "from AccountEntity where user_phone = ? ";
Query query = session.createQuery(hql).setParameter(0, phone);
List list = query.getResultList();
if (list == null || list.size() <= 0) {
return null;
}
System.out.println(((AccountEntity) list.get(0)).getUser_phone());
return (AccountEntity) list.get(0);
}catch (Exception e){
e.printStackTrace();
}finally {
if(session!=null){
session.close();
}
}
return null;
}
@Override
public AccountEntity getAccountByPhoneAndPassword(String phone, String password) {
SessionFactory sessionFactory = SqlSessionFactoryConfig.getInstance();
Session session = sessionFactory.openSession();
try {
String hql = "from AccountEntity where user_phone = ? and user_password = ?";
Query query = session.createQuery(hql).setParameter(0, phone).setParameter(1,password);
List list = query.getResultList();
if (list == null || list.size() <= 0) {
return null;
}
System.out.println(((AccountEntity) list.get(0)).getUser_phone());
return (AccountEntity) list.get(0);
}catch (Exception e){
e.printStackTrace();
}finally {
if(session!=null){
session.close();
}
}
return null;
}
@Override
public boolean saveAccount(AccountEntity accountEntity) {
SessionFactory sessionFactory = SqlSessionFactoryConfig.getInstance();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
session.save(accountEntity);
transaction.commit();
return true;
}catch (Exception e){
transaction.rollback();
e.printStackTrace();
}finally {
if(session!=null){
session.close();
}
}
return false;
}
}
此处实现的有一些low的地方,因为对于hibernate不是特别熟悉~~~见谅啊。。。。。。
看下config包下面的类:
package com.account.config;
public class AccountReturnCode {
/*成功标识*/
private boolean success;
/*返回码*/
private String code;
/*消息,对返回码的补充*/
private String message;
/*附加信息*/
private Object addmessage;
public AccountReturnCode(boolean succ){
this.success = succ;
}
public AccountReturnCode(boolean succ, String cod){
this.success = succ;
this.code = cod;
}
public AccountReturnCode(boolean suc, String cod, String msg){
this.success = suc;
this.code = cod;
this.message = msg;
}
public AccountReturnCode(boolean suc, String cod, String msg, Object addmsg){
this.success = suc;
this.code = cod;
this.message = msg;
this.addmessage = addmsg;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getAddmessage() {
return addmessage;
}
public void setAddmessage(Object addmessage) {
this.addmessage = addmessage;
}
}
package com.account.config;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SqlSessionFactoryConfig {
private static class SqlSessionFactoryInstance{
private final static Configuration configuration = new Configuration().configure("hibernate.cfg.xml");//创建配置对象
private final static SessionFactory sessionFactory = configuration.buildSessionFactory();
}
public static SessionFactory getInstance(){
return SqlSessionFactoryInstance.sessionFactory;
}
}
o哦哦,最后不要忘了resource下面的配置文件:
application.properties:
spring.application.name=account-service
server.port=2222
eureka.client.serviceUrl.defaultZone=http://server1:1111/eureka/,http://server2:1112/eureka/,http://server3:1113/eureka/
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds:5000
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- mysql账户名 -->
<property name="connection.username">root</property>
<!-- mysql密码 -->
<property name="connection.password">123</property>
<!-- mysql驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- mysql连接URL -->
<property name="connection.url">jdbc:mysql://localhost:3306/account_db?useUnicode=true&characterEncoding=UTF-8</property>
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 显示sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化sql语句 -->
<property name="format_sql">true</property>
<!-- 根据需要创建数据库 -->
<property name="hbm2ddl.auto">update</property>
<!-- 最大连接数 -->
<property name="hibernate.c3p0.max_size">100</property>
<!-- 最小连接数 -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- 最大的PreparedStatement的数量 -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- 每次都验证连接是否可用 -->
<property name="hibernate.c3p0.validate">true</property>
<!-- 罗列所有持久化的类名 -->
<mapping class="com.account.db.entity.AccountEntity"/>
</session-factory>
</hibernate-configuration>
logback.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Logback configuration. See http://logback.qos.ch/manual/index.html -->
<configuration scan="true" scanPeriod="10 seconds">
<include resource="org/springframework/boot/logging/logback/base.xml" />
<jmxConfigurator/>
<!--定义日志文件的存储地址和前缀名-->
<property name="LOG_HOME" value="D:/dev/log4jlogs" />
<property name="LOG_PREFIX" value="account-service" />
<!-- 一般信息按照每天生成日志文件 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${LOG_HOME}/${LOG_PREFIX}-info.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- 每天一归档 -->
<fileNamePattern>${LOG_HOME}/${LOG_PREFIX}-info-%d{yyyyMMdd}.log.%i</fileNamePattern>
<!-- 单个日志文件最多500MB, 30天的日志周期,最大不能超过20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n</Pattern>
</encoder>
</appender>
<!--错误信息按照每天生成日志文件-->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<File>${LOG_HOME}/${LOG_PREFIX}-error.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- 每天一归档 -->
<fileNamePattern>${LOG_HOME}/${LOG_PREFIX}-error-%d{yyyyMMdd}.log.%i</fileNamePattern>
<!-- 单个日志文件最多500MB, 30天的日志周期,最大不能超过20GB -->
<maxFileSize>100MB</maxFileSize>
<maxHistory>30</maxHistory>
<totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n</Pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
<!-- 日志输出级别 这样设置不打印日志 -->
<root level="INFO">
<!-- <appender-ref ref="STDOUT" /> -->
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</configuration>
这样就可以直接编译项目,然后运行Main函数啦~~~~~~~~下一小节见。