博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ServiceComb实战
阅读量:6672 次
发布时间:2019-06-25

本文共 10355 字,大约阅读时间需要 34 分钟。

ServiceComb实战combDemo

步骤一、配置POM

4.0.0
cn.qchcolud
combDemo
0.0.1-SNAPSHOT
jar
combDemo
Demo project for ServiceComb-Spring
org.springframework.boot
spring-boot-starter-parent
1.5.12.RELEASE
UTF-8
UTF-8
1.8
org.hibernate
hibernate-validator
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.apache.servicecomb
spring-boot-starter-provider
org.springframework.boot
spring-boot-starter-test
test
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-data-jpa
io.jsonwebtoken
jjwt-api
0.10.5
io.jsonwebtoken
jjwt-impl
0.10.5
runtime
io.jsonwebtoken
jjwt-jackson
0.10.5
runtime
com.fasterxml.jackson.core
jackson-databind
2.8.8.1
org.apache.servicecomb
java-chassis-dependencies
1.0.0-m2
pom
import
org.springframework.boot
spring-boot-maven-plugin
org.springframework.boot
spring-boot-maven-plugin
1.5.12.RELEASE
repackage
target/bin
exec
org.apache.maven.plugins
maven-jar-plugin
2.6
.

步骤二、application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/combDemo?useSSL=falsespring.datasource.username=rootspring.datasource.password=1234spring.jpa.hibernate.ddl-auto=updatespring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

步骤三、工程源码

package cn.qchcolud.combDemo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.apache.servicecomb.springboot.starter.provider.EnableServiceComb;@SpringBootApplication@EnableServiceCombpublic class CombDemoApplication {    public static void main(String[] args) {        SpringApplication.run(CombDemoApplication.class, args);    }}
package cn.qchcolud.combDemo.dto;public class UserDTO {      private String name;      private String password;      public String getName() {        return name;      }      public String getPassword() {        return password;      }      public UserDTO() {      }      public UserDTO(String name, String password) {        this.name = name;        this.password = password;      }    }
package cn.qchcolud.combDemo.entity;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "T_User")public class UserEntity {  @Id  private String name;  private String password;  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public String getPassword() {    return password;  }  public void setPassword(String password) {    this.password = password;  }  public UserEntity() {  }  public UserEntity(String name, String password) {    this.name = name;    this.password = password;  }}
package cn.qchcolud.combDemo.jwt;import java.time.ZonedDateTime;import java.util.Date;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import io.jsonwebtoken.JwtException;import io.jsonwebtoken.Jwts;import static io.jsonwebtoken.SignatureAlgorithm.HS512;@Componentpublic class JwtTokenStore implements TokenStore {  private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenStore.class);  private final String secretKey;  private final int secondsToExpire;  public JwtTokenStore() {    this.secretKey = "someSecretKeyForAuthenticagggggggggggggggggggggtiondfgdgfdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";    this.secondsToExpire = 60 * 60 * 24;  }  public JwtTokenStore(String secretKey, int secondsToExpire) {    this.secretKey = secretKey;    this.secondsToExpire = secondsToExpire;  }  @Override  public String generate(String userName) {    return Jwts.builder().setSubject(userName)        .setExpiration(Date.from(ZonedDateTime.now().plusSeconds(secondsToExpire).toInstant()))        .signWith(HS512, secretKey).compact();  }  @Override  public boolean validate(String token) {    try {      return StringUtils.isNotEmpty(Jwts.parser()       .setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject());    } catch (JwtException | IllegalArgumentException e) {      LOGGER.info("validateToken token : " + token + " failed", e);    }    return false;  }}
package cn.qchcolud.combDemo.jwt;public interface TokenStore {      String generate(String userName);      boolean validate(String token);    }
package cn.qchcolud.combDemo.repository;import org.springframework.data.repository.PagingAndSortingRepository;import org.springframework.stereotype.Repository;import cn.qchcolud.combDemo.entity.UserEntity;@Repositorypublic interface UserRepository extends PagingAndSortingRepository
{ UserEntity findByName(String name);}
package cn.qchcolud.combDemo.service;import org.springframework.http.ResponseEntity;import cn.qchcolud.combDemo.dto.UserDTO;public interface UserService {      ResponseEntity
logon(UserDTO user); ResponseEntity
login(UserDTO user); }
package cn.qchcolud.combDemo.service;import org.apache.commons.lang3.StringUtils;import org.apache.servicecomb.provider.rest.common.RestSchema;import org.apache.servicecomb.swagger.invocation.exception.InvocationException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import cn.qchcolud.combDemo.dto.UserDTO;import cn.qchcolud.combDemo.entity.UserEntity;import cn.qchcolud.combDemo.jwt.TokenStore;import cn.qchcolud.combDemo.repository.UserRepository;import static javax.ws.rs.core.Response.Status.BAD_REQUEST;import static org.springframework.http.HttpHeaders.AUTHORIZATION;@RestSchema(schemaId = "user")@RequestMapping(path = "/")public class UserServiceImpl implements UserService {  private final UserRepository repository;  private final TokenStore tokenStore;  @Autowired  public UserServiceImpl(UserRepository repository, TokenStore tokenStore) {    this.repository = repository;    this.tokenStore = tokenStore;  }  @Override  @PostMapping(path = "logon")  public ResponseEntity
logon(@RequestBody UserDTO user) { if (validateUser(user)) { UserEntity dbUser = repository.findByName(user.getName()); if (dbUser == null) { UserEntity entity = new UserEntity(user.getName(), user.getPassword()); repository.save(entity); return new ResponseEntity<>(true, HttpStatus.OK); } throw new InvocationException(BAD_REQUEST, "user name had exist"); } throw new InvocationException(BAD_REQUEST, "incorrect user"); } @Override @PostMapping(path = "login") public ResponseEntity
login(@RequestBody UserDTO user) { System.out.println("-->"+user.getName()+"--"+user.getPassword()); if (validateUser(user)) { UserEntity dbUser = repository.findByName(user.getName()); if (dbUser != null) { if (dbUser.getPassword().equals(user.getPassword())) { String token = tokenStore.generate(user.getName()); HttpHeaders headers = generateAuthenticationHeaders(token); //add authentication header return new ResponseEntity<>(true, headers, HttpStatus.OK); } throw new InvocationException(BAD_REQUEST, "wrong password"); } throw new InvocationException(BAD_REQUEST, "user name not exist"); } throw new InvocationException(BAD_REQUEST, "incorrect user"); } private boolean validateUser(UserDTO user) { return user != null && StringUtils.isNotEmpty(user.getName()) && StringUtils.isNotEmpty(user.getPassword()); } private HttpHeaders generateAuthenticationHeaders(String token) { HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, token); return headers; }}

转载于:https://blog.51cto.com/14042154/2309593

你可能感兴趣的文章
企业架构,业务架构,数据架构
查看>>
优秀程序员的十个习惯
查看>>
Hello AS400-Cobol
查看>>
Linux-进程间的通信-信号集函数【转】
查看>>
js2word/html2word的简单实现
查看>>
jQuery.extend和jQuery.fn.extend的区别?
查看>>
职业发展
查看>>
Linux下环境变量设置
查看>>
phonegap 安装和使用eclipse
查看>>
ASP.NET MVC使用动态产生meta
查看>>
WIN7无法访问共享打印机及文件的解决办法
查看>>
C语言基础(9)-字符串格式化输入和输出
查看>>
【转】使用import scope解决maven继承(单)问题
查看>>
.NET Core微服务之路:让我们对上一个Demo通讯进行修改,完成RPC通讯
查看>>
你 我 我们 技术 让世界变得更好一些
查看>>
统计建模与R软件-附R原程序
查看>>
安装MSSQL2008出现的问题记录
查看>>
iOS 中NSRunLoop的使用
查看>>
WCF安全:通过 扩展实现用户名密码认证
查看>>
模块化JavaScript设计模式(一)
查看>>