In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to customize guava cache storage token". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Project module analysis
The project is mainly divided into seven modules: user module, commodity module, order module, classification module, shopping cart module, receiving address module and payment module.
Functional analysis core module
Design idea and encapsulation of high multiplexing service response
User module
To solve the problem of horizontal ultra vires and vertical ultra vires, user passwords are encrypted in MD5 plaintext and guava cache is used to store information. User functions mainly include: registration, login, checking whether the user name is valid, password reset, updating user information and so on.
User forgets password and password prompt question and answer design
When users forget their passwords and need to reset their passwords, they need to enter the password prompt questions and answers set during registration, such as: when is your birthday? 1996-08-28, when changing the password, you need to verify that the secret protection question is the same as the answer. When you shopping-mall_v1.0, we use guava cache to store a forgetToken. Compared to setting the validity period of token to 30 minutes (which can be selected according to the project scenario), you need to pass three parameters when resetting the password: username,password,forgetToken. In this case, you need to determine whether the token in the tokenCache obtained by guava is consistent with the forgetToken passed in. Meet the consistent conditions to reset the password successfully!
Custom guava cache storage tokenpublic class TokenCache {/ / create logger private static Logger logger for logback = LoggerFactory.getLogger (TokenCache.class); / / generate prefix public static final String TOKEN_PREFIX for token = "token_" / / declare a static memory block, local cache public static LoadingCache localCache in guava = / / build local cache, call chain, initialCapacity is the initialization capacity of cache, / / maxSize is the maximum memory capacity set by cache ExpireAfterAccess sets the cache to be valid for 12 hours CacheBuilder.newBuilder () .initialCapacity (1000) .maximumSize (10000) .anonymous reAfterAccess (12, TimeUnit.HOURS) / / build to implement an anonymous inner class.build ((new CacheLoader () {/ / this method is the default data loading implementation When get, if key does not have a corresponding value, call this method to load @ Override public String load (String key) throws Exception {/ / Why write the null value of return into a string, because when you use null to go to .pointer, a null pointer exception return "null" will be reported. }})); / / add local cache public static void setKey (String key,String value) {localCache.put (key,value);} / / get local cache public static String getValue (String key) {String value = null; try {value = localCache.get (key) If ("null" .equals (value)) {return null;} return value;} catch (ExecutionException e) {logger.error ("error getting cache getKey () method", e);} return null;}} commodity module
POJO, VO abstract model design, efficient paging and dynamic sorting, using FTP service docking, rich text uploading commodity picture information, commodity module is more important is the product search and dynamic sorting and commodity paging, for example: fuzzy query according to keyword background, according to price ascending / descending order, commodity paging is mainly integrated with pagehelper paging plug-in. Changing the paging plug-in to achieve data paging is relatively efficient and simple in practice. We only need to use PageHelper.startPage (pageNum,pageSize) to achieve it.
Order module
Security vulnerability solution, considering the generation rules of e-commerce commodity order number, the analysis of order status and the design of order enumeration constant, order overtime order processing (delay queue)
Create the encapsulation of the order OrderVO class, which returns all the information that creates the order, including order information, order details (List), address information. When creating an order, you need to verify the status / quantity of the goods in the shopping cart, such as whether it has been removed from the shelves and whether there is insufficient inventory before the verification is successful. After issuing the order successfully, you need to reduce the inventory, and you need to traverse each order Item to get the corresponding goods through the productId of orderItem. Execute product.getStock ()-product.getQuantity () Operation
The generation rule of the order number (timestamp + random number): / * orderNo generation method * * @ return * / private long generateOrderNo () {/ / get the current timestamp long currentTime = System.currentTimeMillis (); / / the number between time + [0PM1000) is [0999] return currentTime + new Random () .nextInt (1000) } regular order closing, and automatic closing of unpaid orders within hour hours
Related implementation logic: first, get the orders in the previous hour hours, query the orders for payment in these orders, and get the goods and quantity in the order to be closed. When you cancel the order, you need to add the quantity of goods (that is, inventory restore), and then set the order status.
@ Override public void closeOrder (int hours) {/ / previous hour hour order Date closeDateTime = DateUtils.addHours (new Date (),-hours); List orderList = orderMapper.selectOrderStatusByCreateTime (Constant.OrderStatusEnum.NO_PAY.getCode (), dateToStr (closeDateTime)); for (Order order: orderList) {List orderItemList = orderItemMapper.getByOrderNo (order.getOrderNo ()) For (OrderItem orderItem: orderItemList) {/ / get the number of items to be shut down: be sure to use the primary key where condition to prevent table locking, and must support MySQL's InnoDB engine Integer stock = productMapper.selectStockByProductId (orderItem.getProductId ()) / / considering that the items in the generated order have been deleted, there is no need to update if (stock = = null) {continue;} Product product = new Product (); product.setId (orderItem.getProductId ()); product.setStock (stock + orderItem.getQuantity ()) ProductMapper.updateByPrimaryKeySelective (product);} orderMapper.closeOrderByOrderId (order.getId ()); log.info ("close order orderNo: {}", order.getOrderNo ());}} classification module
Using recursive algorithm, the weight of complex objects and the design of infinite hierarchical tree structure.
Get the classification child node (level): when the parent and classification parentId pass 0, the search is for the child classification with the node
Get the classification id and the recursive child node classification id (return itself and the child nodes below it, assuming that the next-level child node of 0-> 10-> 100-> 1000Magi 0 is 10-10, the next-level node of 100100 is 1000, and the performance is return: 0 (itself)-> 10-> 100-> 100-> 100), and the recursive query algorithm is designed as follows:
/ * Recursively query the id of this node and the id logic implementation of the child node * * @ param categoryId * @ return * / @ Override public ServerResponse selectCategoryAndChildrenById (Integer categoryId) {Set categorySet = Sets.newHashSet (); this.findChildCategoryRecursive (categorySet, categoryId); / / finally, return categoryIdList categoryIdList = Lists.newArrayList () If (categoryId! = null) {for (Category categoryItem: categorySet) {categoryIdList.add (categoryItem.getId ());}} return ServerResponse.createBySuccess (categoryIdList);} / * * Recursive query algorithm, adjust yourself, we use the Set collection to return, can arrange weight, why do you want to rewrite Category's HashCode and equals *? When two objects are the same, that is, equals returns true, their hashCode must be the same, but when the * hashCode of two objects is the same, the two objects are not necessarily the same, so it is concluded that when using the Set collection, pay attention to overriding the equals and hashCode * methods. * / private Set findChildCategoryRecursive (Set categorySet, Integer categoryId) {Category category = categoryMapper.selectByPrimaryKey (categoryId); if (category! = null) {categorySet.add (category);} / / Recursive algorithm to find the child node List categoryList = categoryMapper.selectCategoryChildrenByParentId (categoryId) For (Category categoryItem: categoryList) {/ / call your own findChildCategoryRecursive (categorySet, categoryItem.getId ());} return categorySet;} / / mapper select from tb_category where parent_id = # {parentId} shopping cart module
The shopping cart module examines the encapsulation of high-reuse logical methods, the calculation reuse and encapsulation of the total price of goods, the use of BigDecimal types to solve the problem of loss of accuracy in business operations, the single selection / reverse selection, all selection / all selection functions of a shopping cart, and multiple items in a shopping cart. When adding a shopping cart, it is necessary to check whether the quantity of each item purchased exceeds the inventory or exceeds the inventory. The quantity purchased cannot be set to the quantity selected by the user, but the stock quantity, and the total amount can only be calculated by multiplying the existing inventory quantity by the unit price when calculating the price.
Receiving address module
Data binding and object binding, upgrade and consolidate the ultra vires problem. When deleting an address, in order to prevent horizontal ultra vires, we cannot send only one shippingId, so the world cannot use the deleteByPrimaryKey () method generated by mybatis to delete. Just imagine: when the user is logged in, if only one shippingId is needed to delete, then the problem of ultra vires will arise when the shippingId is not passed. That is, the so-called horizontal ultra vires, in order to prevent horizontal ultra vires, we need to customize a method to bind the harvest address to the user, such as: custom deleteByUserIdAndShippingId () method to achieve. (the same is true of address updates.)
Payment module
Alipay SDK source code analysis, analysis of Alipay pay Demo payment process, the integration of Alipay into the project, including: payment QR code generation, code scanning payment, the logic of payment is:
Step 1: check the payment status of the order. If order.getStatus () connects the QR code to the QR code picture,
3. Enter payment password to complete payment-> return payment success information-> if payment is successful, return asynchronous information (merchant returns success)
4. Call alipay.trade.query () to query order status-> but query results-> if payment success (code=10000) is returned, the process ends
5. If the payment is not completed within the specified time-> call alipay.trade.cancel to close the transaction
This is the end of "how to customize guava cache Storage token". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.