SpringBoot集成环境配置

多环境配置

yml

server:
 port: 8080
 servlet:
  context-path: /weichuang
spring:
  profiles:
    active: test # 环境选择

---
server:
  port: 8080
  servlet:
    context-path: /weichuang
spring:
  profiles: dev # 环境名

---
server:
  port: 8081
spring:
  profiles: test # 环境名

MySQL

Maven依赖

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--jdbc-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--Druid德鲁伊数据源-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.19</version>
</dependency>

application

yml

spring:
#  MySQL
  datasource:
    username: root
    password: ROOT
    #加入时区报错,就增加一个时区的配置就ok了===serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/spring?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    #com.mysql.jdbc.Driver===5版本的数据库
    #com.mysql.cj.jdbc.Driver===8版本以上的数据库
    driver-class-name: com.mysql.cj.jdbc.Driver
    #指定druid德鲁伊数据源
    type: com.alibaba.druid.pool.DruidDataSource

测试类

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class Springboot05MybatisApplicationTests {

    @Autowired
    private DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }
}

Mybatis

Maven依赖

<!--springboot整合mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

application

yml

# mybatis配置
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml    # mapper映射文件位置
  type-aliases-package: com.kgc.pojo    # 实体类所在的位置
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #用于控制台打印sql语句

Redis

Maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application

yml

spring:
# Redis
  redis:
  	database: 13 #选库
    host: 192.168.25.110
    port: 6379
    password:
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 500
        min-idle: 0
    lettuce:
      shutdown-timeout: 0ms

Config

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;
@Configuration
public class RedisConfig {
    @Bean @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

RedisUtils==可选

package com.chuang.qywxweichuang.util;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil{

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    /**
     * 指定缓存失效时间
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key,Long time){
        try {
            if(time > 0){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e1){
            e1.printStackTrace();
            return false;
        }
    }
    /**
     * 获取key的过期时间
     * @param key
     * @return
     */
    public long getExpire(String key){
        return redisTemplate.getExpire(key);
    }
    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public boolean hashKey(String key){
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e2){
            e2.printStackTrace();
            return false;
        }
    }
    /**
     * 删除缓存
     * @param key
     */
    public void del(String... key){
        if (key != null && key.length > 0) {
            if(key.length == 1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
                //redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
//=====================================String========================================
    /**
     * 普通缓存获取
     * @param key
     * @return
     */
    public Object get(String key){
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * 普通放入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,Object value){
        try {
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e3){
            e3.printStackTrace();
            return false;
        }
    }
    /**
     * 普通放入缓存并设置时效
     * @param key
     * @param value
     * @param time  time > 0 设置时效, time < 0 设置无限期
     * @return
     */
    public boolean set(String key,Object value,long time){
        try{
            if (time > 0) {
                redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else{
                redisTemplate.opsForValue().set(key,value);
            }
            return true;
        }catch (Exception e4){
            e4.printStackTrace();
            return false;
        }
    }
    /**
     * 递增
     * @param key
     * @param data
     * @return
     */
    public long incr(String key,long data){
        if(data < 0){
            throw  new RuntimeException("递增因子 不能小于0");
        }
        return  redisTemplate.opsForValue().increment(key,data);
    }

    public long decr(String key,long data){
        if(data < 0){
            throw  new RuntimeException("递减因子,不能小于0");
        }
        return redisTemplate.opsForValue().increment(key,-data);
    }
    //===================================Hash==================================

    /**
     * hashKey
     * @param key
     * @param keyItem
     * @return
     */
    public Object getHash(String key,String keyItem){
        return redisTemplate.opsForHash().get(key,keyItem);
    }

    /**
     * 获取hashkey所有的键值
     * @param key
     * @return
     */
    public Map<Object, Object> hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * hashSet
     * @param key
     * @param map
     * @return
     */
    public boolean hsset(String key,Map<Object,Object> map){
        try {
            redisTemplate.opsForHash().putAll(key,map);
            return true;
        }catch (Exception e4){
            e4.printStackTrace();
            return false;
        }
    }

    /**
     * hashSet 设置时效
     * @param key
     * @param map
     * @param time
     * @return
     */
    public boolean hsset(String key,Map<Object,Object> map, Long time){
        try {
            redisTemplate.opsForHash().putAll(key,map);
            if (time > 0) {
                expire(key,time);
            }
            return true;
        }catch (Exception e5){
            e5.printStackTrace();
            return false;
        }
    }

    /**
     * 向hash表中插入键值
     * @param key
     * @param itemKey
     * @param value
     * @return
     */
    public boolean hset(String key,String itemKey,Object value){
        try {
            redisTemplate.opsForHash().put(key,itemKey,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向hash表中插入键值,设置时效
     * @param key
     * @param itemKey
     * @param value
     * @param time
     * @return
     */
    public boolean hset(String key,String itemKey,Object value,long time){
        try {
            redisTemplate.opsForHash().put(key,itemKey,value);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的项
     * @param key 不能为null
     * @param item 不能为null,可以是多个
     */
    public void hdel(String key,Object...item){
        redisTemplate.opsForHash().delete(key,item);
    }

    /**
     * 判断hash表中有没有键,项
     * @param key
     * @param item
     * @return
     */
    public boolean hHashKey(String key,Object item){
        return redisTemplate.opsForHash().hasKey(key,item);
    }

    /**
     * 递增,值如果不存在就会创建一个,并把创建的值返回
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double haIncr(String key,Object item,double by){
        if(by < 0){
            throw  new RuntimeException("递增因子不能小于0");
        }
        return redisTemplate.opsForHash().increment(key,item,by);
    }

    /**
     * 递减,值如果不存在就会创建一个,并把创建的值返回
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double haDenr(String key,Object item,double by){
        return redisTemplate.opsForHash().increment(key,item,-by);
    }
//===================================set============================================

    /**
     * 根据key获取set
     * @param key
     * @return
     */
    public Set<Object> sGet(String key){
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 从一个set中查询value是否存在
     * @param key
     * @param value
     * @return
     */
    public boolean sHashKey(String key,Object value){
        return redisTemplate.opsForSet().isMember(key,value);
    }

    /**
     * 将set数据放入缓存
     * @param key
     * @param values
     * @return 成功的个数
     */
    public long sSet(String key,Object...values){
        try {
            return redisTemplate.opsForSet().add(key,values);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存并给key设置时效
     * @param key 键
     * @param time key 时效
     * @param values 值,可以是多个
     * @return 成功的个数
     */
    public long sSet(String key, Long time, Object... values){
        try {
            Long count = redisTemplate.opsForSet().add(key,values);
            if (time > 0) {
                expire(key,time);
            }
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存长度
     * @param key
     * @return
     */
    public long sSize(String key){
        try {
            return redisTemplate.opsForSet().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除set缓存中的值
     * @param key 键
     * @param values 值可以是多个
     * @return 移除的个数
     */
    public long sRemove(String key,Object... values){
        try {
            return redisTemplate.opsForSet().remove(key,values);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
//======================================list=========================

    /**
     * 获取list缓存中的值
     * @param key 键
     * @param start 开始
     * @param end 结束  从0到-1显示所有的值
     * @return
     */
    public List<Object> lGet(String key,long start,long end){
        try {
            return redisTemplate.opsForList().range(key,start,end);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存长度
     * @param key
     * @return
     */
    public long lSize(String key){
        try {
            return redisTemplate.opsForList().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return  0;
        }
    }

    /**
     * 根据index获取list缓存的值
     * @param key 键
     * @param index -1代表表尾,-2代表倒数第二个元素 以此类推
     * @return
     */
    public Object lIndex(String key,long index){
        try {
            return redisTemplate.opsForList().index(key,index);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 把list放入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key,Object value){
        try {
            redisTemplate.opsForList().leftPush(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 把list放入缓存,设置key的时效
     * @param key
     * @param time
     * @param value
     * @return
     */
    public boolean lSet(String key,long time,Object value){
        try {
            redisTemplate.opsForList().leftPush(key,value);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list缓存中具体值
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lUpdate(String key,Long index,Object value){
        try {
            redisTemplate.opsForList().set(key,index,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key
     * @param count
     * @param value
     * @return
     */
    public long lRomve(String key,Long count,Object value){
        try {
            long remove = redisTemplate.opsForList().remove(key,count,value);
            return remove;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }
}

测试类

查看更多命令

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class Springboot05MybatisApplicationTests {


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

  
    @Test
    void test(){
        redisTemplate.opsForValue().set("mykey","myvalue");
        System.out.println(redisTemplate.opsForValue().get("mykey"));
    }
}

Nutz

Maven依赖

<!--Springboot整合Nutz-->
<dependency>
    <groupId>org.nutz</groupId>
    <artifactId>nutz-plugins-spring-boot-starter</artifactId>
    <version>1.r.66</version>
</dependency>
<!--阿里的数据连接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>
<!--数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

application

yml

spring:
  datasource:
    username: root
    password: ROOT
    #加入时区报错,就增加一个时区的配置就ok了===serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/nutzdemo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    #com.mysql.jdbc.Driver===5版本的数据库
    #com.mysql.cj.jdbc.Driver===8版本以上的数据库
    driver-class-name: com.mysql.cj.jdbc.Driver
    #指定druid德鲁伊数据源
    type: com.alibaba.druid.pool.DruidDataSource
nutz:
  json:
    auto-unicode: false
    quote-name: true
    ignore-null: true
    null-as-emtry: true
    enabled: true
    mode: compact
  dao:
    runtime:
      create: true #自动创建表
      migration: false #根据bena自动更新表结构
      basepackage: com.chuang.qywxweichuang.pojo  #扫描bean
    sqlmanager:
      paths:

Config

import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;

@Configuration
public class DaoConfiguration {

    @Bean
    @Primary
    public Dao getDao(DataSource dataSource) {
        // 创建一个NutDao实例,在真实项目中, NutDao通常由ioc托管, 使用注入的方式获得.
        Dao dao = new NutDao(dataSource);
        return dao;
    }
}

实体类==创建表

import org.nutz.dao.entity.annotation.*;

@Table("t_person")   // 声明了Person对象的数据表
public class Person { // 不会强制要求继承某个类
    @Id       // 表示该字段为一个自增长的Id,注意,是数据库表中自增!!
    private int id; // @Id与属性名称id没有对应关系.

    @Name    // 表示该字段可以用来标识此对象,或者是字符型主键,或者是唯一性约束
    private String name;

    @Column      // 表示该对象属性可以映射到数据库里作为一个字段
    private int age;
    //省略get、set

测试类

查看更多命令

import com.chuang.qywxweichuang.pojo.Person;
import org.junit.jupiter.api.Test;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.impl.SimpleDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class QywxweichuangApplicationTests {
    // 创建一个NutDao实例,在真实项目中, NutDao通常由ioc托管, 使用注入的方式获得.
    @Autowired
    private Dao dao;
    @Test
    void contextLoads() {
        // 创建表
        dao.create(Person.class,false);// false的含义是,如果表已经存在,就不要删除重建了.
        Person person = new Person();
        person.setName("ABC");
        person.setAge(20);
        dao.insert(person);
        System.out.println(person.getId());
    }
}

Thymeleaf

Maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

application

yml

spring:
 # thymeleaf
 thymeleaf:
   prefix: classpath:/templates/
   suffix: .html
   mode: HTML5
   encoding: UTF-8
   servlet:
     content-type: text/html
   cache: false

Config

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class WebMvcConfig implements WebMvcConfigurer{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

Swgeer2

Maven依赖

application

yml

Config

Controller

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我也不想摸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值