In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
How to implement Service & Zuul configuration & Test, I believe many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Design and implementation of DAO layer
Here we use Spring DATA JPA to implement database operations. Of course, you can also use Mybatis, which is the same. We still take user table operations as an example:
/ * * AdUserRepository for user database operation interface * inherits from JpaRepository. The first parameter, AdUser, represents the class definition of the entity class to be operated. The second parameter, Long, represents the primary key type of the class * * @ author Isaac.Zhang * / public interface AdUserRepository extends JpaRepository {/ * get the user * * @ param username name * @ return user object * / AdUser findByUserName (String username) based on the user name List findAllByUserName (String userName);}
The default implementation method of JPARepository. If we only inherit JpaRepository without implementing the specific operation method, we can also do the CRUD operation by using its default method, as follows:
Functional Service implementation
Create service package, still take user actions as an example, create com.sxzhongf.ad.service.IUserService and com.sxzhongf.ad.service.impl.UserServiceImpl,UserServiceImpl to implement IUserService.
Create an IUserService interface
/ * * IUserService for user service * * @ author Isaac.Zhang | if * / public interface IUserService {/ * create user interface * * @ param userRequestVO {@ link UserRequestVO} * @ return {@ link UserResponseVO} * @ throws AdException error * / UserResponseVO createUser (UserRequestVO userRequestVO) throws AdException; List findAllByUserName (String userName);}
Use the IUserService interface
/ * * UserServiceImpl for user service * * @ author Isaac.Zhang | Ruochu * / @ Slf4j@Servicepublic class UserServiceImpl implements IUserService {private final AdUserRepository userRepository; @ Autowired public UserServiceImpl (AdUserRepository userRepository) {this.userRepository = userRepository } / * create user * * @ param userRequestVO {@ link UserRequestVO} * @ return result {@ link UserResponseVO} * / @ Override @ Transactional public UserResponseVO createUser (UserRequestVO userRequestVO) throws AdException {if (! userRequestVO.validate ()) {log.error ("Request params error: {}", userRequestVO); throw new AdException (Constants.ErrorMessage.REQUEST_PARAM_ERROR) AdUser existUser = userRepository.findByUserName (userRequestVO.getUserName ()); if (existUser! = null) {log.error ("{} user is not exist.", userRequestVO.getUserName ()); throw new AdException (Constants.ErrorMessage.USER_EXIST);} AdUser user = userRepository.save (new AdUser (userRequestVO.getUserName (), CommonUtils.md5 (userRequestVO.getUserName () Log.info ("current user is: {}", user); return new UserResponseVO (user.getUserId (), user.getUserName (), user.getToken (), user.getCreateTime (), user.getUpdateTime ()); @ Override public List findAllByUserName (String userName) {return userRepository.findAllByUserName (userName);}}
Create a data transfer object (dto/vo)
In fact, many people here will be very depressed, do not know the difference between these names, personal advice is not to worry about, dto (data transfer object), that is, we pass in each layer of the object, vo in the presentation layer operation of the object. But this is just a name, its essence is an object, can you pass it to the DAO layer? Of course, you can pass individual fields. Therefore, there is no need to dwell on this kind of information, sometimes it can be counterproductive.
/ * UserRequestVO for create user request object VO * * @ author Isaac.Zhang | Ruochu * / @ Data@AllArgsConstructor@NoArgsConstructorpublic class UserRequestVO {private String userName; public boolean validate () {return! StringUtils.isEmpty (userName);}}-/ * UserResponseVO for user responds to VO * * @ author Isaac.Zhang | Ruochu * / @ Data@AllArgsConstructor@NoArgsConstructorpublic class UserResponseVO {private Long userId; private String userName; private String token Private Date createTime; private Date updateTime;}
Because the error message may be the same, we extract a constant class to encapsulate it.
/ * Constants for TODO * * @ author Isaac.Zhang | Ruochu * / public class Constants {/ * * General error message exception class * / public static class ErrorMessage {public static final String REQUEST_PARAM_ERROR = "request parameter exception"; public static final String USER_EXIST = "user already exists"; public static final String USER_NOT_EXIST = "user does not exist";}}
Create a utility class com.sxzhongf.ad.common.utils.CommonUtils under Common Project to md5 encrypt the user username to obtain token information.
/ * * CommonUtils for tool class * * @ author Isaac.Zhang | if the beginning * / @ Slf4jpublic class CommonUtils {/ * md5 encryption * / public static String md5 (String value) {return DigestUtils.md5Hex (value). ToUpperCase ();}}
Refer to the implementation of creating the user and implement other table operations in turn.
Controller implementation
Still take the implementation of user functions as an example:
/ * * UserController for user controller * * @ author Isaac.Zhang | Ruochu * / @ RestController@Slf4j@RequestMapping ("/ user") public class UserController {@ Autowired private IUserService userService; @ PostMapping (path = "/ create") public UserResponseVO createUser (@ RequestBody UserRequestVO requestVO) throws AdException {log.info ("ad-sponsor: createUser-> {}", JSON.toJSONString (requestVO)); return userService.createUser (requestVO) @ GetMapping (path = "/ get") public CommonResponse getUserList (@ Param (value = "username") String username) throws AdException {log.info ("ad-sponsor: getUserList-> {}", JSON.toJSONString (username)); return new CommonResponse (userService.findAllByUserName (username));}}
Configure the advertisement delivery system in the gateway
In the configuration of the delivery system, we have configured a path such as server.servlet.context-path:/ad-sponsor, which means that all paths requesting the current system need to have ad-sponsor, such as http://xxx/ad-sponsor/user/get?username=yyy, which is required for gateway requests. According to the above, we configure our current delivery system in the gateway service:
Spring: application: name: ad-gateway-zuulserver: port: 1111eureka: client: service-url: defaultZone: http://server1:7777/eureka/,http://server2:8888/eureka/, Http://server3:9999/eureka/ instance: hostname: ad-gateway-zuul### the following is important information zuul: ignored-services:'*'# filter all requests In addition to the services declared in routes below # configure gateway routing rules routes: sponsor: # Custom service routing name path: / ad-sponsor/** serviceId: mscx-ad-sponsor # Micro service name strip-prefix: false search: # Custom service routing name path: / ad-search/** serviceId: mscx-ad- in routing Search # Microservice name strip-prefix: false prefix: / gateway/api strip-prefix: false # does not intercept the path set by prefix: / gateway/api Default forwarding truncates the configured prefix
Test
Direct access to the delivery system
Call curl-G http://localhost:7000/ad-sponsor/user/get?username=Isaac%20Zhang and return the result:
{code: 0, / / unify and successfully mark message: "success", / / Unified processing result message data: [/ / specific object information {userId: 10, userName: "Isaac Zhang", token: "2D3ABB6F2434109A105170FB21D00453", userStatus: 1, createTime: 1561118873000, updateTime: 1561118873000}]}
Called through the gateway
Because I added the prefix prefix: / gateway/api to the gateway configuration, we need to add this prefix information when we visit, otherwise we will report a 404 error.
Curl-G http://localhost:1111/gateway/api/ad-sponsor/user/get?username=Isaac%20Zhang, we found that the results did not show as we expected.
Bogon:~ zhangpan$ http://localhost:1111/gateway/api/ad-sponsor/user/get?username=Isaac%20Zhang-bash: http://localhost:1111/gateway/api/ad-sponsor/user/get?username=Isaac%20Zhang: No such file or directory
Why? Let's take a look at the log:
2019-07-27 20 INFO 4419.093 INFO 4766-[nio-1111-exec-4] c.s.a.g.filter.ValidateTokenFilter: GET request to http://localhost:1111/gateway/api/ad-sponsor/user/get2019-07-27 20 c.s.a.g.filter.ValidateTokenFilter 4419.093 WARN 4766-[nio-1111-exec-4] c.s.a.g.filter.ValidateTokenFilter: access token is empty2019-07-27 20 c.s.a.g.filter.ValidateTokenFilter 4419.098 INFO 4766-[nio-1111-exec-4] c.s.ad.gateway.filter.AccessLogFilter: Request "/ gateway/api/ad-sponsor/user/get" spent: 0 seconds.2019-07-27 20 Request 48 c.s.ad.gateway.filter.AccessLogFilter 37.801 INFO 4766-[trap-executor-0] c.n.d.s.r.aws.ConfigClusterResolver: Resolving eureka endpoints via configuration
We can see clearly, ValidateTokenFilter: access token is empty, why is there such an error? That's because when I configured the gateway, I added an intercept:
/ * * ValidateTokenFilter for service token verification * * @ author Isaac.Zhang * / @ Slf4j@Componentpublic class ValidateTokenFilter extends ZuulFilter {. @ Override public Object run () throws ZuulException {RequestContext ctx = RequestContext.getCurrentContext (); HttpServletRequest request = ctx.getRequest (); log.info (String.format ("% s request to% s", request.getMethod (), request.getRequestURL (). ToString ()); Object accessToken = request.getHeader ("accessToken") / / .getParameter ("accessToken"); if (accessToken = = null) {log.warn ("access token is empty"); ctx.setSendZuulResponse (false); ctx.setResponseStatusCode (401); / / ctx.setResponseBody (body) to edit the returned body content return null;} log.info ("access token ok"); return null;}}
Looking at the code, we found that we will get the accessToken parameter from RequestHeader. If we do not provide it, of course we will report an error. Next, we provide this parameter and try again:
Bogon:~ zhangpan$ curl-H "accessToken:true" http://localhost:1111/gateway/api/ad-sponsor/user/get?username=Isaac%20Zhang--- returns {"code": 0, "message": "success", "data": [{"userId": 10, "userName": "Isaac Zhang", "token": "2D3ABB6F2434109A105170FB21D00453", "userStatus": 1, "createTime": 1561118873000, "updateTime": 1561118873000}]}
At this point, the simple function of our advertising delivery system has been fully implemented, and can be forwarded through the gateway.
After reading the above, have you mastered how to implement Service & Zuul configuration & Test? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.