Springboot 手動搭建項目 --redis配置&日誌完善+使用者名稱

來源:互聯網
上載者:User

標籤:資訊   合格   erb   Servle   顯示   setname   等等   輸出   try   

項目git網址:https://github.com/David-BIQI/manage.git(項目使用比較新的springboot2.0 還有jdk8 )

參照的代碼規範:https://github.com/xwjie/PLMCodeTemplate.git (這個是一套能夠落地的代碼規範,跟著風哥學習很多)

redis配置
  • 如何配置
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-redis</artifactId></dependency>
#redis設定  redis:    host: localhost    port: 6379    database: 0
  • redis的格式轉換

也有轉成json存放的,寫的demo中就有stringRedisTemplate存放的,下面是序列化的使用

package com.common.redis;import org.springframework.core.convert.converter.Converter;import org.springframework.core.serializer.support.DeserializingConverter;import org.springframework.core.serializer.support.SerializingConverter;import org.springframework.data.redis.serializer.RedisSerializer;import org.springframework.data.redis.serializer.SerializationException;/** * redis序列化的工具類 */public class RedisObjectSerializer implements RedisSerializer<Object> {  private Converter<Object, byte[]> serializer = new SerializingConverter();  private Converter<byte[], Object> deserializer = new DeserializingConverter();  static final byte[] EMPTY_ARRAY = new byte[0];  @Override  public Object deserialize(byte[] bytes) {    if (isEmpty(bytes)) {      return null;    }    try {      return deserializer.convert(bytes);    } catch (Exception ex) {      throw new SerializationException("Cannot deserialize", ex);    }  }  @Override  public byte[] serialize(Object object) {    if (object == null) {      return EMPTY_ARRAY;    }    try {      return serializer.convert(object);    } catch (Exception ex) {      return EMPTY_ARRAY;    }  }  private boolean isEmpty(byte[] data) {    return (data == null || data.length == 0);  }}
package com.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;import com.biqi.dto.UserDto;import com.common.redis.RedisObjectSerializer;@Configurationpublic class RedisConfig {    @Bean    JedisConnectionFactory jedisConnectionFactory() {        return new JedisConnectionFactory();    }    @Bean    public RedisTemplate<String, UserDto> redisTemplate(RedisConnectionFactory factory) {        RedisTemplate<String, UserDto> template = new RedisTemplate<String, UserDto>();        template.setConnectionFactory(jedisConnectionFactory());        template.setKeySerializer(new StringRedisSerializer());        template.setValueSerializer(new RedisObjectSerializer());        return template;    }}
  • redis的讀與取,這樣就能實現redis中的簡單的讀寫功能
    @Autowired    private StringRedisTemplate stringRedisTemplate;    @Autowired    private RedisTemplate<String, UserDto> redisTemplate;    public String saveAndGet(String name) {        stringRedisTemplate.opsForValue().set(name, name);        String temp = stringRedisTemplate.opsForValue().get(name);        return temp;    }    public Boolean saveUserBySerializer(Integer id) {        User user = userService.getUserByid(id);        notNull(user,"使用者資訊不存在");        UserDto temp = new UserDto();        temp.setName(user.getName());        temp.setPhone(user.getPhone());        redisTemplate.opsForValue().set(user.getName(), temp);        return true;    }

 

 日誌的完善,
  • 如何寫好日誌 曉風輕 項目aop的修改

1.不要依賴debug,多依賴日誌。

別人面對對象編程,你面對debug編程。有些人無論什麼語言,最後都變成了面對debug編程。哈哈。這個習慣非常非常不好!debug會讓你寫代碼的時候偷懶不打日誌,而且很浪費時間。改掉這個惡習。

2. 代碼開發測試完成之後不要急著提交,先跑一遍看看日誌是否看得懂。

日誌是給人看的,只要熱愛編程的人才能成為合格程式員,不要匆匆忙忙寫完功能測試ok就提交代碼,日誌也是功能的一部分。要有精益求精的工匠精神!

  • local怎麼的使用,完善日誌,在filter的時候判斷得到登入使用者的使用者名稱,放入到MD5中,然後在log日誌中添加上使用者的資訊
    @Override        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)                throws IOException, ServletException {            HttpServletRequest request = (HttpServletRequest) srequest;            String url = request.getRequestURI();            // Login的時候跳過,不然都進入其他            if (LOGIN_URL.equals(url)) {                System.out.println("這是登入的方法咯 ");                filterChain.doFilter(srequest, sresponse);            } else {                HttpSession session = request.getSession(true);                if (session == null) {                    throw new UnloginException();                }                // 從session中擷取使用者資訊放到工具類中                String userToken = (String) session.getAttribute(UserUtil.KEY_USER);                UserUtil.setUser(userToken);                filterChain.doFilter(srequest, sresponse);            }        }
    public static void setUser(String userid) {        tlUser.set(userid);        // 把使用者資訊放到log4j        MDC.put(KEY_USER, userid);    }
    <!-- 控制台輸出 -->    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">            <!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:層級從左顯示5個字元寬度%msg:日誌訊息,%n是分行符號 -->            <pattern>%d{MM-dd HH:mm:ss} %X{user} [%thread] %-5level-%logger{50} -%msg%n</pattern>        </encoder>    </appender>

效果如下

這樣日誌使用者資訊基本完成,不過要寫好日誌,還有一番功夫需要做,一看日誌就知道業務實現,成功失敗的次數等等,pick myself up !!!

 

Springboot 手動搭建項目 --redis配置&日誌完善+使用者名稱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.