1. 程式人生 > 實用技巧 >使用IDEA快速搭建基於Maven的SpringBoot專案(整合使用Redis)

使用IDEA快速搭建基於Maven的SpringBoot專案(整合使用Redis)

使用IDEA快速搭建基於Maven的SpringBoot專案(整合使用Redis)

迫於好久沒寫部落格心慌慌,隨便寫個簡單版的筆記便於查閱。

新建專案

新建專案 然後起名 繼續next netx finish。

首先附上demo的專案結構圖

配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId
> <version>1.5.9.RELEASE</version> <!-- 我這裡用的1.5.9 --> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.blaze</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</
version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.9.RELEASE</version> </dependency> <dependency> <groupId>com.didispace</groupId> <artifactId>spring-boot-starter-swagger</artifactId> <version>1.1.0.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- 分頁外掛 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <!-- druid資料庫連線池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <!--tomcat--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<version>1.2.4.RELEASE</version>--> </dependency> <!--fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.50</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <finalName>blaze</finalName> </build> </project>

構建demo目錄結構

application.properties改成application.yml格式的配置檔案

server:
  port: 8080


spring:
  datasource:
    name: mysql_test
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相關配置
    druid:
      #監控統計攔截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本屬性
      url: jdbc:mysql://localhost:3306/blaze_test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
      username: root
      password: root
      #配置連線池 初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #獲取連線等待超時時間
      max-wait: 60000
      #間隔多久進行一次檢測,檢測需要關閉的空閒連線
      time-between-eviction-runs-millis: 60000
      #一個連線在池中最小生存的時間
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      #開啟PSCache,並指定每個連線上PSCache的大小。oracle設為true,mysql設為false。分庫分表較多推薦設定為false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20
  #redis相關配置 host把埠加進去(詳見RedisConfig的jedisConnectionFactory)
  redis:
    database: 0
    host: 193.168.10.102:6379
    port: 6379
    password:
    timeout: 500
    pool:
      max-idle: 8
      max-wait: -1
      max-active: 8
      min-idle: 0

#mybatis:
#  mapper-locations: classpath:mapper/*.xml
#  type-aliases-package: com.blaze.model

#pagehelper
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  returnPageInfo: check

#swagger
swagger:
  title: spring-boot-starter-swagger
  description: Starter for swagger 2.x
  version: 1.1.0.RELEASE
  license: Apache License, Version 2.0
  license-url: https://www.apache.org/licenses/LICENSE-2.0.html
  terms-of-service-url: https://github.com/github-sun/Funs
  base-package: com.blaze.demo
  contact:
    name: blaze
    email: [email protected]

UserDomain.java

package com.blaze.demo.model;

import java.io.Serializable;

/**
 * create by zy 2019/5/30 10:35
 * TODO
 */
public class UserDomain implements Serializable {
    private int id;
    private String userId;
    private String userName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

UserDao.java

package com.blaze.demo.dao;

import com.blaze.demo.model.UserDomain;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * create by zy 2019/5/30 10:28
 * TODO
 */
@Mapper
public interface UserDao {
    //新增user 如果已經存在相同的userName 則不插入資料
    @Insert("INSERT INTO tb_user(id,user_id,user_name) SELECT #{id}, #{userId},#{userName} FROM DUAL WHERE NOT EXISTS (SELECT user_name FROM tb_user WHERE user_name=#{userName})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    @Transactional
    int insert(UserDomain record);


    //查詢
    @Select("SELECT id, user_id as userId, user_name as userName FROM tb_user")
    List<UserDomain> selectUsers();
}

UserService.java

package com.blaze.demo.service;

import com.blaze.demo.model.UserDomain;
import com.github.pagehelper.PageInfo;

/**
 * create by zy 2019/5/30 10:30
 * TODO
 */
public interface UserService {
    /**
     * 新增user
     * @param user
     * @return
     */
    int addUser(UserDomain user);

    /**
     * 分頁查詢userList
     * @param pageNum
     * @param pageSize
     * @return
     */
    PageInfo<UserDomain> findAllUser(int pageNum, int pageSize);
}

UserServiceImpl.java

package com.blaze.demo.service.impl;

import com.blaze.demo.dao.UserDao;
import com.blaze.demo.model.UserDomain;
import com.blaze.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * create by zy 2019/5/30 10:28
 * TODO
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;//這裡會報錯,但是並不會影響

    @Override
    public int addUser(UserDomain user) {

        return userDao.insert(user);
    }

    /*
     * 這個方法中用到了我們開頭配置依賴的分頁外掛pagehelper
     * 很簡單,只需要在service層傳入引數,然後將引數傳遞給一個外掛的一個靜態方法即可;
     * pageNum 開始頁數
     * pageSize 每頁顯示的資料條數
     * */
    @Override
    public PageInfo<UserDomain> findAllUser(int pageNum, int pageSize) {
        //將引數傳給這個方法就可以實現物理分頁了,非常簡單。
        PageHelper.startPage(pageNum, pageSize);
        List<UserDomain> userDomains = userDao.selectUsers();
        PageInfo result = new PageInfo(userDomains);
        return result;
    }
}

UserController.java

package com.blaze.demo.controller;

import com.blaze.demo.model.UserDomain;
import com.blaze.demo.service.UserService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * create by zy 2019/5/30 10:28
 * TODO
 * CrossOrigin 允許跨域訪問
 */
@Api(value = "", tags = {"使用者管理介面"})
@CrossOrigin(maxAge = 3600, origins = "*")
@RestController
@RequestMapping(value = "/user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping("/add")
    public int addUser(UserDomain user) {
        logger.info("-------------blaze add user--------------");
        return userService.addUser(user);
    }

    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize) {
        logger.info("-------------blaze select user--------------");
        return userService.findAllUser(pageNum, pageSize);
    }
}

DemoApplication.java

package com.blaze.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 此處加上@EnableSwagger2註解 才能使用swagger
 * 加上@EnableCaching 使用redis
 */
@SpringBootApplication
@EnableSwagger2
@EnableCaching
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

整合使用redis

配置在application.yml中

RedisConfig.java

package com.blaze.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.core.env.MapPropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * create by zy 2019/5/30 14:19
 * TODO
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWaitMillis;

    @Value("${spring.redis.password}")
    private String password;


    @Bean
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        return jedisPoolConfig;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {

        if (host.split(",").length == 1) {
            //單機版
            logger.info("-----------------blaze redis 單機版-------------------------");
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setHostName(host.split(":")[0]);
            factory.setPort(Integer.valueOf(host.split(":")[1]));
            factory.setPassword(password);
            factory.setTimeout(timeout);
            factory.setPoolConfig(getJedisPoolConfig());
            return factory;
        } else {
            //叢集
            logger.info("-----------------blaze redis 叢集版-------------------------");
            JedisConnectionFactory jcf = new JedisConnectionFactory(getClusterConfiguration());
            jcf.setPoolConfig(getJedisPoolConfig());
            jcf.setPassword(password); //叢集的密碼認證
            return jcf;
        }
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        logger.info("===cacheManager successed");
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
        //設定快取過期時間
        redisCacheManager.setDefaultExpiration(1800);//
        return redisCacheManager;
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> getRedisTemplate() {
        logger.info("===redisTemplate successed");
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class));
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }


    @Bean
    public RedisClusterConfiguration getClusterConfiguration() {
        if (host.split(",").length > 1) {
            //如果是host是叢集模式的才進行以下操作
            Map<String, Object> source = new HashMap<String, Object>();
            source.put("spring.redis.cluster.nodes", host);
            source.put("spring.redis.cluster.timeout", timeout);
            //source.put("spring.redis.cluster.max-redirects", redirects);
            source.put("spring.redis.cluster.password", password);
            return new RedisClusterConfiguration(new
                    MapPropertySource("RedisClusterConfiguration", source));
        } else {
            return null;
        }
    }

}

RedisCommon.java

package com.blaze.demo.utils;

import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * create by zy 2019/5/30 14:33
 * TODO 隨便寫的 有點簡單粗暴 湊合看吧
 */
public class RedisCommon {
    @Resource
    private RedisTemplate redisTemplate;

    public RedisCommon(RedisTemplate client) {
        this.redisTemplate = client;
    }


    /**
     * 值型別 put
     *
     * @param key
     * @param val
     * @return
     */
    public boolean setObjectVal(String key, Object val) {
        try {
            redisTemplate.boundValueOps(key).set(val);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 值型別put 帶過期時間
     *
     * @param key
     * @param val
     * @param expries
     * @param timeUnit
     * @return
     */
    public boolean setObjectValExpries(String key, Object val, int expries, TimeUnit timeUnit) {
        try {
            redisTemplate.boundValueOps(key).set(val, expries, timeUnit);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 值型別get
     *
     * @param key
     * @return
     */
    public Object getObjectVal(String key) {
        try {
            return redisTemplate.boundValueOps(key).get();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * set型別put
     *
     * @param key
     * @param val
     * @return
     */
    public boolean setSetVal(String key, Set val) {
        try {
            for (Object o : val) {
                redisTemplate.boundSetOps(key).add(o);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * set型別get
     *
     * @param key
     * @return
     */
    public Set getSetVal(String key) {
        try {
            return redisTemplate.boundSetOps(key).members();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 刪除set中的一項
     *
     * @param key
     * @param opt
     * @return
     */
    public boolean removeSetOpt(String key, Object opt) {
        try {
            redisTemplate.boundSetOps(key).remove(opt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public boolean setLeftListVal(String key, List<Object> val) {
        try {
            for (Object o : val) {
                redisTemplate.boundListOps(key).leftPush(o);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setRightListVal(String key, List<Object> val) {
        try {
            for (Object o : val) {
                redisTemplate.boundListOps(key).rightPush(o);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public List getListVal(String key, int start, int end) {
        try {
            return redisTemplate.boundListOps(key).range(start, end);
        } catch (Exception e) {
            return null;
        }
    }

    public Object getListVal(String key, int index) {
        try {
            return redisTemplate.boundListOps(key).index(index);
        } catch (Exception e) {
            return null;
        }
    }

    public boolean removeListOpt(String key, int index, Object opt) {
        try {
            redisTemplate.boundListOps(key).remove(index, opt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //hash型別的不寫了


    /**
     * 刪除
     *
     * @param key
     * @return
     */
    public boolean delete(String key) {
        try {
            redisTemplate.delete(key);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

測試

前提:確保配置檔案中配置的mysql和redis都正常

因為使用了swagger 可直接執行 訪問http://localhost:8080/swagger-ui.html測試

也可直接訪問對應的urlhttp://localhost:8080/user/all

測試redis

package com.blaze.demo;

import com.alibaba.fastjson.JSON;
import com.blaze.demo.model.UserDomain;
import com.blaze.demo.utils.RedisCommon;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Resource
    private RedisTemplate redisTemplate;

    @Test
    public void blaze() {
        RedisCommon redisUtil = new RedisCommon(redisTemplate);
        redisUtil.setObjectValExpries("blaze", "123456", 30, TimeUnit.SECONDS);
        System.out.println(redisUtil.getObjectVal("blaze"));
        
        UserDomain user = new UserDomain();
        user.setId(1);
        user.setUserId("2333");
        user.setUserName("blazeZzz");
        redisUtil.setObjectValExpries("blazeZzz", JSON.toJSONString(user), 30, TimeUnit.SECONDS);
        System.out.println(redisUtil.getObjectVal("blazeZzz"));
    }
}

結果

以上。

posted @ 2019-05-31 10:03 青衫仗劍 閱讀(...) 評論(...) 編輯 收藏