Skip to content

Commit

Permalink
更新服务消费者示例
Browse files Browse the repository at this point in the history
  • Loading branch information
micyo202 committed Jun 16, 2020
1 parent 4fe0632 commit 6d62098
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ public class ConsumerDemoController extends BaseController {

@ApiOperation("初始化")
@GetMapping("/init")
public Result init() {
public Result<String> init() {

String msg = applicationName + " -> port: " + port + ", version: " + version + ", foo: " + foo;

Result providerInitResult = providerDemoFeignClient.initFromProvider();
Result<String> providerInitResult = providerDemoFeignClient.initFromProvider();
if (providerInitResult.getCode() != ResponseCode.SUCCESS) {
return Result.failure(msg + ", " + providerInitResult.getMsg());
} else {
Expand All @@ -90,7 +90,7 @@ public Result init() {
@ApiOperation("Feign服务调用,返回Hi文本内容")
@ApiParam(name = "name", value = "名称(默认lion)", defaultValue = "lion", required = true)
@GetMapping("/feign/hi")
public Result feignHi(String name) {
public Result<String> feignHi(String name) {
log.info("Consumer -> 服务消费者 /feign/hi");
return providerDemoFeignClient.hiFromProvider(name);
}
Expand All @@ -102,10 +102,10 @@ public Result feignHi(String name) {
@ApiParam(name = "name", value = "名称(默认lion)", defaultValue = "lion", required = true)
@SentinelResource(value = "ribbonHi", fallback = "ribbonHiFallback")
@RequestMapping(value = "/ribbon/hi", method = {RequestMethod.GET, RequestMethod.POST})
public Result ribbonHi(String name) {
public Result<String> ribbonHi(String name) {

String method = this.getRequest().getMethod();
Result result = null;
Result<String> result = null;
if ("GET".equals(method)) {
Map<String, Object> params = new HashMap<>(2);
params.put("name", name);
Expand All @@ -129,28 +129,28 @@ public Result ribbonHi(String name) {
/**
* Ribbon服务熔断降级
*/
public Result ribbonHiFallback(String name) {
public Result<String> ribbonHiFallback(String name) {
return Result.failure("Ribbon Hi: '" + name + "', fallback sentinel");
}

@ApiOperation("Sentinel流量控制")
@GetMapping("/sentinel/block")
@SentinelResource(value = "sentinelBlock", blockHandler = "sentinelBlockHandler", blockHandlerClass = BlockHandler.class)
public Result sentinelBlock() {
public Result<String> sentinelBlock() {
return Result.success("This is sentinel control service flow");
}

@ApiOperation("Sentinel服务熔断降级")
@GetMapping("/sentinel/fallback")
@SentinelResource(value = "sentinelFallback", fallback = "sentinelFallback", fallbackClass = FallbackHandler.class)
public Result sentinelFallback() {
public Result<String> sentinelFallback() {
throw new LionException("This is sentinel control service fallback");
//return Result.failure(500, "This is sentinel control service fallback");
}

@ApiOperation("获取用户凭证信息")
@RequestMapping(value = "/principle", method = {RequestMethod.GET, RequestMethod.POST})
public Result getPrinciple(OAuth2Authentication oAuth2Authentication, Principal principal, Authentication authentication) {
public Result<OAuth2Authentication> getPrinciple(OAuth2Authentication oAuth2Authentication, Principal principal, Authentication authentication) {
log.info(oAuth2Authentication.getUserAuthentication().getAuthorities().toString());
log.info(oAuth2Authentication.toString());
log.info("principal.toString() " + principal.toString());
Expand All @@ -163,22 +163,22 @@ public Result getPrinciple(OAuth2Authentication oAuth2Authentication, Principal
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
//@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/admin", method = {RequestMethod.GET, RequestMethod.POST})
public Result getAdmin() {
public Result<String> getAdmin() {
return Result.success("当前用户,拥有Admin权限可访问");
}

@ApiOperation("角色控制 - 需拥有user角色")
//@PreAuthorize("hasAuthority('ROLE_USER')")
@PreAuthorize("hasRole('USER')")
@RequestMapping(value = "/user", method = {RequestMethod.GET, RequestMethod.POST})
public Result getUser() {
public Result<String> getUser() {
return Result.success("当前用户,拥有User权限可访问......");
}

@ApiOperation("Redisson分布式锁")
@Locker
@RequestMapping(value = "/lock", method = {RequestMethod.GET, RequestMethod.POST})
public Result lock() {
public Result<String> lock() {
try {
log.info("执行锁中业务逻辑");
Thread.sleep(5000);
Expand All @@ -193,7 +193,7 @@ public Result lock() {

@ApiOperation("异步线程执行任务")
@GetMapping("/async")
public Result async() {
public Result<String> async() {
asyncTaskService.asyncJob("A");
asyncTaskService.asyncJob("B");
return Result.success("异步线程任务调用完成,请查看日志结果");
Expand All @@ -204,13 +204,13 @@ public Result async() {

@ApiOperation("AMQP消息发送/接收")
@RequestMapping(value = "/amqp", method = {RequestMethod.GET, RequestMethod.POST})
public Result amqp() {
public Result<Object> amqp() {
Map<String, Object> map = new HashMap<>(6);
map.put("id", 1);
map.put("msg", "AMQP发送消息");
map.put("valid", true);
map.put("sendTime", DateUtil.getCurrentDateTime());
Result result = Result.success(map);
Result<Map<String, Object>> result = Result.success(map);

amqpSender.send(result);

Expand All @@ -220,31 +220,31 @@ public Result amqp() {
@ApiOperation("区块链 - 开采追加块链")
@ApiParam(name = "data", value = "块内容")
@PostMapping("/blockchain/mined")
public Result blockChainMined(@RequestParam(name = "data") String data) {
public Result<String> blockChainMined(@RequestParam(name = "data") String data) {
String hash = BlockChain.minedBlockChain(data);
return Result.success(hash);
}

@ApiOperation("区块链 - 解析块链")
@ApiParam(name = "blockHash", value = "需解析的块Hash散列值")
@PostMapping(value = "/blockchain/decrypt/{blockHash}")
public Result blockChainDecrypt(@PathVariable String blockHash) {
public Result<String> blockChainDecrypt(@PathVariable String blockHash) {
String blockchainJson = BlockChain.decryptBlockchain(blockHash);
return Result.success(blockchainJson);
}

@ApiOperation("文件上传")
@ApiParam(name = "file", value = "附件内容")
@PostMapping("/upload")
public Result upload(HttpServletRequest request) {
public Result<List<String>> upload(HttpServletRequest request) {
List<String> list = fileUpload(request);
return Result.success(list);
}

@ApiOperation("文件下载")
@ApiParam(name = "fileName", value = "文件名称", required = true)
@GetMapping("/download/{fileName}")
public Result download(@PathVariable String fileName, HttpServletResponse response) {
public Result<String> download(@PathVariable String fileName, HttpServletResponse response) {
boolean result = fileDownload(fileName, response);
return result ? Result.success("文件下载成功") : Result.failure("文件下载失败");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
* TempMybatisController
* TODO
* Mybatis示例
*
* @author Yanzheng (https://github.com/micyo202)
* @date 2019/04/15
Expand All @@ -53,7 +54,7 @@ public class TempMybatisController extends BaseController {
@ApiParam(name = "num", value = "插入数据条数", defaultValue = "5", required = true)
@RequestMapping(value = "/save/{num}", method = {RequestMethod.GET, RequestMethod.POST})
@Transactional
public Result save(@PathVariable int num) {
public Result<String> save(@PathVariable int num) {

if (0 >= num) {
return Result.failure("[num] 参数不正确,取值范围必须大于 0 的整数(例:/save/3)");
Expand All @@ -74,7 +75,7 @@ public Result save(@PathVariable int num) {
tempMybatis.setId(DateUtil.getTimestamp());
} else {
//主键冲突,触发事务回滚
tempMybatis.setId(new Long(1));
tempMybatis.setId(1L);
}

// 若使用 Try Catch 需要手动回滚事务:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Expand All @@ -100,7 +101,7 @@ public Result save(@PathVariable int num) {

@ApiOperation("Mybatis自定义SQL方式查询")
@RequestMapping(value = "/custom/sql", method = {RequestMethod.GET, RequestMethod.POST})
public Result customSql() {
public Result<List<TempMybatis>> customSql() {
return Result.success(tempMybatisService.listByCustomSql());
}

Expand All @@ -111,11 +112,11 @@ public Result customSql() {
@ApiImplicitParam(name = "pageSize", value = "每页条数", defaultValue = "3", dataType = "String")
})
@RequestMapping(value = "/page/{version}/{pageNum}/{pageSize}", method = {RequestMethod.GET, RequestMethod.POST})
public Result page(@PathVariable String version, @PathVariable int pageNum, @PathVariable int pageSize) {
public Result<PageInfo<TempMybatis>> page(@PathVariable String version, @PathVariable int pageNum, @PathVariable int pageSize) {

String statement = "com.lion.demo.consumer.mapper.TempMybatisMapper.listByCustomSql";

PageInfo pageInfo;
PageInfo<TempMybatis> pageInfo;

String orderBy = "name DESC,id ASC";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@

import com.lion.common.base.controller.BaseController;
import com.lion.common.constant.ResponseCode;
import com.lion.common.result.Result;
import com.lion.common.exception.LionException;
import com.lion.common.result.Result;
import com.lion.common.util.DateUtil;
import com.lion.demo.consumer.feign.ProviderDemoFeignClient;
import com.lion.demo.consumer.entity.TempOrder;
import com.lion.demo.consumer.feign.ProviderDemoFeignClient;
import com.lion.demo.consumer.service.TempOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
Expand Down Expand Up @@ -57,7 +57,7 @@ public class TempOrderController extends BaseController {
@RequestMapping(value = "/commit", method = {RequestMethod.GET, RequestMethod.POST})
@GlobalTransactional
@Transactional
public Result commit() {
public Result<String> commit() {
place("product-1", 1);
return Result.success("下单成功");
}
Expand All @@ -69,7 +69,7 @@ public Result commit() {
@RequestMapping(value = "/rollback", method = {RequestMethod.GET, RequestMethod.POST})
@GlobalTransactional
@Transactional
public Result rollback() {
public Result<String> rollback() {
place("product-1", 1);
throw new LionException("全局事务 -> 模拟回滚(数据正常)...");
}
Expand All @@ -80,7 +80,7 @@ public Result rollback() {
@ApiOperation(value = "无全局事务,无法回滚,数据错乱", notes = "执行:插入订单表、扣减库存表")
@RequestMapping(value = "/exception", method = {RequestMethod.GET, RequestMethod.POST})
@Transactional
public Result exception() {
public Result<String> exception() {
place("product-1", 1);
throw new LionException("无全局事务 -> 无法回滚(数据已错乱)...");
}
Expand All @@ -100,7 +100,7 @@ private void place(String productCode, int count) {
.setUpdateTime(LocalDateTime.now());

tempOrderService.save(tempOrder);
Result deduct = providerDemoFeignClient.deductFromProvider(productCode, count);
Result<String> deduct = providerDemoFeignClient.deductFromProvider(productCode, count);
if (deduct.getCode() != ResponseCode.SUCCESS) {
throw new LionException(deduct.getMsg());
}
Expand Down

0 comments on commit 6d62098

Please sign in to comment.