SpringCloud框架搭建+实际例子+讲解+系列三

上一节讲解了,父项目的搭建和服务管制中心子项目的搭建,能够正常启动我们的服务管制中心,现在来看一下我的服务提供者子项目:

(2)服务提供者(Application-Service)

SpringCloud框架搭建+实际例子+讲解+系列三_第1张图片

pom文件如下所示:



    4.0.0
    
        mymall-master
        mymall-master
        1.0-SNAPSHOT
    

    account-service
    account-service
    1.0-SNAPSHOT

    
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.cloud
            spring-cloud-starter-eureka
        
        
        
            mysql
            mysql-connector-java
            5.1.39
        
        
        
            org.hibernate
            hibernate-core
            5.2.6.Final
        
        
        
            commom-moudle
            common-moudle
            1.0-SNAPSHOT
        
    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Brixton.RELEASE
                pom
                import
            
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            repackage
                        
                    
                
            
        
    

服务启动类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:




  
    
    root

    
    123

    
    com.mysql.jdbc.Driver

    
    jdbc:mysql://localhost:3306/account_db?useUnicode=true&characterEncoding=UTF-8

    
    org.hibernate.dialect.MySQLDialect

    
    true

    
    true

    
    update

    
    100
    
    5
    
    120
    
    100
    
    120
    
    2
    
    true

    
    

  

logback.xml:





    
	
    
    
    

    
    
        ${LOG_HOME}/${LOG_PREFIX}-info.log
        
            
            ${LOG_HOME}/${LOG_PREFIX}-info-%d{yyyyMMdd}.log.%i
            
            100MB
            30
            20GB
        
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n
        
    

    
    
        
            ERROR
        
        ${LOG_HOME}/${LOG_PREFIX}-error.log
        
            
            ${LOG_HOME}/${LOG_PREFIX}-error-%d{yyyyMMdd}.log.%i
            
            100MB
            30
            20GB
        
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} -%msg%n
        
    

    
        
            
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
        
    
	  
    
    
       
        
        
    

这样就可以直接编译项目,然后运行Main函数啦~~~~~~~~下一小节见。




你可能感兴趣的:(SpringCloud框架搭建+实际例子+讲解+系列三)