springboot 2.6.13 快速启动系列(持续更新)

1.redis

pom

        
            org.springframework.boot
            spring-boot-starter-data-redis
        

application.yml

spring:
  redis:
    host: localhost
    password: 123456
    port: 6379
    timeout: 5000
    database: 1

配置类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author  {@literal [email protected]}
 * 继承 CachingConfigurerSupport,为了自定义生成 KEY 的策略。可以不继承。
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    private int timeToLive = 3*60*60*1000;

    /**
     * 配置Jackson2JsonRedisSerializer序列化策略
     * */
    private Jackson2JsonRedisSerializer serializer() {
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();

        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }


    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        redisTemplate.setValueSerializer(serializer());

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        redisTemplate.setKeySerializer(stringRedisSerializer);

        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(serializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }




    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 缓存有效期
                .entryTtl(Duration.ofDays(timeToLive))
                // 使用StringRedisSerializer来序列化和反序列化redis的key值
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer()))
                // 禁用空值
                .disableCachingNullValues();

        return RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
    }
} 
  

简单示例

    @Autowired
    private RedisTemplate redisTemplate;

        
    @Test
    void testTwo() throws IOException {

        User user = new User("1","2");
        //  手动序列化
        redisTemplate.opsForValue().set(user.getId(), user);
        User user1 = (User) redisTemplate.opsForValue().get(user.getId());

        System.out.println(user1.toString());

    }

2.mysql ---- mybatis-plus

pom

        
            org.projectlombok
            lombok
        
        
        
            com.mysql
            mysql-connector-j
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.2
        
        
            com.baomidou
            mybatis-plus-generator
            3.5.3.1
        

application.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/DatabaseName?useUnicode=true&characterEncoding=utf8
    driverClassName: com.mysql.cj.jdbc.Driver

easycode模板

controller

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Controller")

##保存文件(宏定义)
#save("/controller", "Controller.java")

##包路径(宏定义)
#setPackageSuffix("controller")

##定义服务名
#set($serviceName = $!tool.append($!tool.firstLowerCase($!tableInfo.name), "Service"))

##定义实体对象名
#set($entityName = $!tool.firstLowerCase($!tableInfo.name))

import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

##表注释(宏定义)
#tableComment("表控制层")
@RestController
@RequestMapping("$!tool.firstLowerCase($!tableInfo.name)")
public class $!{tableName}{
    @Autowired
    private $!{tableInfo.name}Service $!{serviceName};
}

dao

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Mapper")

##保存文件(宏定义)
#save("/mapper", "Mapper.java")

##包路径(宏定义)
#setPackageSuffix("mapper")

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;
import org.apache.ibatis.annotations.Mapper;
##表注释(宏定义)

#tableComment("表数据库访问层")
@Mapper
public interface $!{tableName} extends BaseMapper<$!tableInfo.name> {

}

entity

##导入宏定义
$!{define.vm}

##保存文件(宏定义)
#save("/entity", ".java")

##包路径(宏定义)
#setPackageSuffix("entity")

##自动导入包(全局变量)
$!{autoImport.vm}

import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
##表注释(宏定义)
#tableComment("表实体类")
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuppressWarnings("serial")
public class $!{tableInfo.name} {
#foreach($column in $tableInfo.fullColumn)
    #if(${column.comment})//${column.comment}#end

    private $!{tool.getClsNameByFullName($column.type)} $!{column.name};
#end



}

service

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("Service")

##保存文件(宏定义)
#save("/service", "Service.java")

##包路径(宏定义)
#setPackageSuffix("service")

import com.baomidou.mybatisplus.extension.service.IService;
import $!{tableInfo.savePackageName}.entity.$!tableInfo.name;

##表注释(宏定义)
#tableComment("表服务接口")
public interface $!{tableName} extends IService<$!tableInfo.name> {

}

serviceImpl

##导入宏定义
$!{define.vm}

##设置表后缀(宏定义)
#setTableSuffix("ServiceImpl")

##保存文件(宏定义)
#save("/service/impl", "ServiceImpl.java")

##包路径(宏定义)
#setPackageSuffix("service.impl")

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import $!{tableInfo.savePackageName}.mapper.$!{tableInfo.name}Mapper;
import $!{tableInfo.savePackageName}.entity.$!{tableInfo.name};
import $!{tableInfo.savePackageName}.service.$!{tableInfo.name}Service;
import org.springframework.stereotype.Service;

##表注释(宏定义)
#tableComment("表服务实现类")
@Service("$!tool.firstLowerCase($tableInfo.name)Service")
public class $!{tableName} extends ServiceImpl<$!{tableInfo.name}Mapper, $!{tableInfo.name}> implements $!{tableInfo.name}Service {

}

3.elasticsearch 

pom


            
                org.springframework.boot
                spring-boot-starter-data-elasticsearch
            

application.tml

spring:
  data:
    elasticsearch:
      client:
        reactive:
          endpoints: http://ip:9200
          socket-timeout: 15000
          connection-timeout: 10000
  elasticsearch:
    rest:
      uris: http://ip:9200

使用示例

entity

@Data
@Document(indexName = "my_log")
public class EsLog implements Serializable {
    @Id
    private String id;

    /**
     * 业务
     */
    private String module;
    /**
     * 请求的方法地址
     */
    private String className;
    /**
     * 创建时间
     */
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @Field(type = FieldType.Date, index = false, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;
    /**
     * 时间戳 查询时间范围时使用
     */
    private Long timeMillis;
    /**
     * 请求参数
     */
    private Object[] args;
    /**
     * ip地址
     */
    private String IpAddr;
    /**
     * 执行时间
     */

    private String executeTime;
    public EsLog(String module, String className, Object[] args, String ipAddr, String executeTime) {
        this.id = UUID.randomUUID().toString().replace("-","");
        this.module = module;
        this.className = className;
        this.args = args;
        IpAddr = ipAddr;
        this.executeTime = executeTime;
        this.createTime = new Date();
        this.timeMillis = System.currentTimeMillis();
    }
    public EsLog() {
    }
}

dao

import com.example.myelasticsearch.entity.EsLog;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Service;

/**
 * esc dao
 */
@Mapping
public interface EsLogDao extends ElasticsearchRepository {
    /**
     * 通过类型获取
     * @param type
     * @return
     */
}

简单使用

    @GetMapping("/t")
    public String t(){
        EsLog esLog = new EsLog();

        esLogDao.save(esLog);
        return "t";
    }

你可能感兴趣的:(spring,boot,java,前端)