zoukankan      html  css  js  c++  java
  • Springboot 手动搭建项目 --redis配置&日志完善+用户名

    项目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;
    
    @Configuration
    public 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 !!!

  • 相关阅读:
    data structure,(ADT)
    正交和投影的理解
    高阶函数(包含偏函数)简要介绍
    名字与对象之间的建立引用与解除引用,Python中不可修改对象等,换行加文档字符串,
    迭代器
    CrashCourse 笔记
    列表生成式的进化版——生成器以及iterator
    高代小笔记——关于共轭,欧式空间,双线性函数
    高等代数的笔记杂记——Jordan标准形,Jordan块
    Centos6版本搭建Cobbler,实现自动化部署多版本系统
  • 原文地址:https://www.cnblogs.com/xiebq/p/9231845.html
Copyright © 2011-2022 走看看