後端開發得到的一些小技巧和方法

(1)通過使用request中的getAttribute屬性獲取絕對的url
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String url = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
// 這裏的url的值爲 : /user/{id}/score/{sid}

// 與 request.getRequestURI();   URI: /user/1/score/2
// 和request.getRequestURL().toString();   URL: http://localhost:8180/user/1/score/2

(2)aop 使用Around操作時,對於異常處理有兩種方法
如果不對其進行其他操作可以直接在方法名後面拋出異常()throw throwable{};
如果相對其進行其他操作,比如記錄錯誤日誌等等,可以使用try catch,catch最後使用throw new RuntimeException(throwable)進行異常拋出;

推薦使用下方
   @Around("definePointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            Object ret = proceedingJoinPoint.proceed();
            logger.info("獲取的返回值爲: " + JSONObject.toJSONString(ret));
            return ret;
        } catch (Throwable throwable) {
            throw new RuntimeException(throwable);
      }
(3)
在某些不能直接訪問數據庫的場景或者 需要獲取bean的場景
比如使用mybatis的攔截器,則獲取用戶的信息,不能直接通過controller->service->dao進行查詢
因爲經過了dao層,


但是可以在此處 直接通過註解
@Resource
ApplicationContext applicationContext;
然後
applicationContext.getBean(String name); 進行強轉 轉爲需要的Bean,比如
UserDao userDao = (UserDao)applicationContext.getBean("UserDao");
然後這裏就可以使用userDao進行邏輯操作了
(4)對於執行一次並且全局調用的對象,可以將其放入到Threadlocal中
,類似於PageHelper的startPage()
方法封裝的一樣,會封裝以一個ThreadLocal對象,下次取直接獲取即可
這裏例子是,登錄的時候 將用戶userId存入到ThreadLocal,在一些攔截器中直接通過get方法獲取即可

import org.springframework.stereotype.Component;

/**
 * 管理登錄用戶的工具類
 *
 * @since 2019-12-07 17:10
 **/
@Component
public class AccessUserManager {
    /**
     * 用來存儲當前訪問用戶ID的線程變量池
     */
    private static ThreadLocal<Integer> accessUserIdThread = new ThreadLocal<>();

    /**
     * 取出當前訪問的用戶ID
     *
     * @return java.lang.Integer 當前訪問的用戶ID
     * @date 2019-12-07
     */
    public static Integer getAccessUserId() {
        Integer accessUserId = accessUserIdThread.get();
        if (accessUserId != null) {
            return accessUserId;
        } else {
            throw new NullPointerException("當前訪問的用戶ID爲空");
        }
    }

    /**
     * 存入當前訪問的用戶ID
     *
     * @param accessUserId 用戶ID
     * @date 2019-12-07
     */
    public static void setAccessUserId(Integer accessUserId) {
        accessUserIdThread.set(accessUserId);
    }

    /**
     * 清除當前線程保存的用戶ID
     *
     * @date 2019-12-07
     */
    public static void clearAccessUserId() {
        accessUserIdThread.remove();
    }
}

4.StringUtils文檔 https://www.jianshu.com/p/3c12ae6a4909

5.在編寫一些需要效率的sql語句,可以考慮使用原生的jdbc,只需要通過dataSource獲取connect進行數據庫操作即可

    @Autowired
    DataSource dataSource;

  Connection connection = dataSource.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from error_info");
        while(resultSet.next()){
            ErrorInfo errorInfo = new ErrorInfo();
            int id = resultSet.getInt("id");
            String userName = resultSet.getString("user_name");
            String error = resultSet.getString("error");
            String position = resultSet.getString("position");
            Date create_time = resultSet.getDate("create_time");
            errorInfo.setId(id).setUserName(userName).setError(error).setPosition(position).setCreateTime(create_time);
            System.out.println(JSON.toJSONString(errorInfo));
        }

6.重新加載數據庫連接,可以使用下面的方法,這裏是將配置文件中的數據進行解密

    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) throws Exception {
        // userName = root  password = admin
        String username = dataSourceProperties.getUsername();
        String password = dataSourceProperties.getPassword();
        dataSourceProperties.setUsername(SymmetricEncoder.decrypt(username));
        dataSourceProperties.setPassword(SymmetricEncoder.decrypt(password));
        return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章