Spring Boot 搭建以及集成 StringRedisTemplate

来源:互联网 发布:js push array[0] 问题 编辑:程序博客网 时间:2024/05/17 02:04

Spring Boot搭建以及集成StringRedisTemplate,其中RedisServiceImpl里面给了一部分的StringRedisTemplate的方法以及注释.具体工程如下:

结构如图:

这里写图片描述

spring boot的工程结构可以在Spring Initializr网站上面导出需要的模板:点击跳转

先引入Spring boot的依赖以及StringRedisTemplate的依赖包,pom如下:

<?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>    <groupId>spring-boot-01</groupId>    <artifactId>spring-boot-01</artifactId>    <version>1.0-SNAPSHOT</version>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.6.RELEASE</version>        <relativePath/>    </parent>    <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-web</artifactId>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-tomcat</artifactId>            <!--<scope>provided</scope>-->        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-test</artifactId>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-data-redis</artifactId>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>

Spring Boot和Dubbo一样需要一个main方法来启动,如下:

package cn.lijie;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * User: lijie * Date: 2017/8/16 * Time: 10:23 */@SpringBootApplicationpublic class MyApplication {    public static void main(String[] args) {        SpringApplication.run(MyApplication.class, args);    }}

spring boot可以很快搭建一个RestFul的接口框架,然后写一个测试的Controller:

package cn.lijie.controller;import cn.lijie.service.impl.RedisServiceImpl;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;/** * User: lijie * Date: 2017/8/16 * Time: 10:25 */@RestController@EnableAutoConfigurationpublic class MyController {    protected static Logger logger = LoggerFactory.getLogger(MyController.class);    @Autowired    RedisServiceImpl redis;    @RequestMapping("/")    public String getHelloWorld() {        logger.info("------------------------------  return hello world!");        return "hello world!";    }    @RequestMapping("/get/{key}/{value}")    @ResponseBody    public Object getJson(@PathVariable String key, @PathVariable String value) {        logger.info("------------------------------  input key is:{}  ,and value is:{} ", key, value);        Map<String, String> m = new HashMap<String, String>();        m.put(key, value);        return m;    }    @RequestMapping("/redis/{key}/{value}")    @ResponseBody    public Object redis(@PathVariable String key, @PathVariable String value) {        logger.info("------------------------------  input key is:{}  ,and value is:{} ", key, value);        redis.set(key, value);        return redis.get(key);    }}

将StringRedisTemplate的方法封装到Service层,其中接口如下:

package cn.lijie.service;import java.util.Set;/** * User: lijie * Date: 2017/8/16 * Time: 11:43 */public interface RedisService {    /**     * 设置key value     *     * @param key     * @param value     */    public void set(String key, String value);    /**     * 设置key value 以及过期时间     *     * @param key     * @param value     * @param time     */    public void set(String key, String value, long time);    /**     * 获取value     *     * @param key     * @return     */    public String get(String key);    /**     * 增长器     *     * @param key     * @param step     * @return     */    public long incLong(String key, long step);    /**     * hash 获取     *     * @param hKey     * @param key     * @return     */    public String getHash(String hKey, String key);    /**     * hash 设置     *     * @param hKey     * @param key     * @param value     */    public void setHash(String hKey, String key, String value);    /**     * 获取所有的hash     *     * @param hKey     * @return     */    public Set<String> getHashByHKey(String hKey);    /**     * 删除某个hash     *     * @param hKey     * @param key     * @return     */    public long deleteHash(String hKey, String key);    /**     * 左出栈     *     * @param key     * @return     */    public String getListPopLeft(String key);    /**     * 右出栈     *     * @param key     * @return     */    public String getListPopRight(String key);    /**     * 左入栈     *     * @param key     * @param value     */    public void setLeftPush(String key, String value);    /**     * 右入栈     *     * @param key     * @param value     */    public void setRightPush(String key, String value);    /**     * 获取list长度     *     * @param key     * @return     */    public long getListSize(String key);    /**     * 删除栈的值     * count> 0:删除等于从左到右移动的值的第一个元素     * count< 0:删除等于从右到左移动的值的第一个元素     * count = 0:删除等于value的所有元素     *     * @param key     * @param count     * @param value     * @return     */    public long removeList(String key, long count, String value);    /**     * 存储set     *     * @param key     * @param value     * @return     */    public long setSet(String key, String value);    /**     * 删除set     *     * @param key     * @param value     * @return     */    public long deleteSet(String key, String value);    /**     * 获取set     *     * @param key     * @return     */    public String getSet(String key);    /**     * 获取set长度     *     * @param key     * @return     */    public long getSetSize(String key);}

具体的实现类如下:

package cn.lijie.service.impl;import cn.lijie.service.RedisService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.*;import org.springframework.stereotype.Component;import javax.annotation.Resource;import java.util.Set;import java.util.concurrent.TimeUnit;/** * User: lijie * Date: 2017/8/16 * Time: 11:44 */@Componentpublic class RedisServiceImpl implements RedisService {    @Autowired    StringRedisTemplate redisTemplate;    @Resource(name = "redisTemplate")    ValueOperations<String, String> redisValue;    @Resource(name = "redisTemplate")    SetOperations<String, String> redisSet;    @Resource(name = "redisTemplate")    HashOperations<String, String, String> redisHash;    @Resource(name = "redisTemplate")    ListOperations<String, String> redisList;    //---------------------------------------------------------------ValueOperations    /**     * 设置key value     *     * @param key     * @param value     */    public void set(String key, String value) {        redisValue.set(key, value);    }    /**     * 设置key value 以及过期时间     *     * @param key     * @param value     * @param time     */    public void set(String key, String value, long time) {        redisValue.set(key, value, time, TimeUnit.MILLISECONDS);    }    /**     * 获取value     *     * @param key     * @return     */    public String get(String key) {        return redisValue.get(key);    }    /**     * 增长器     *     * @param key     * @param step     * @return     */    public long incLong(String key, long step) {        return redisValue.increment(key, step);    }    //---------------------------------------------------------------HashOperations    /**     * hash 获取     *     * @param hKey     * @param key     * @return     */    public String getHash(String hKey, String key) {        return redisHash.get(hKey, key);    }    /**     * hash 设置     *     * @param hKey     * @param key     * @param value     */    public void setHash(String hKey, String key, String value) {        redisHash.put(hKey, key, value);    }    /**     * 获取所有的hash     *     * @param hKey     * @return     */    public Set<String> getHashByHKey(String hKey) {        return redisHash.keys(hKey);    }    /**     * 删除某个hash     *     * @param hKey     * @param key     * @return     */    public long deleteHash(String hKey, String key) {        return redisHash.delete(hKey, key);    }    //---------------------------------------------------------------ListOperations    /**     * 左出栈     *     * @param key     * @return     */    public String getListPopLeft(String key) {        return redisList.leftPop(key);    }    /**     * 右出栈     *     * @param key     * @return     */    public String getListPopRight(String key) {        return redisList.rightPop(key);    }    /**     * 左入栈     *     * @param key     * @param value     */    public void setLeftPush(String key, String value) {        redisList.leftPush(key, value);    }    /**     * 右入栈     *     * @param key     * @param value     */    public void setRightPush(String key, String value) {        redisList.rightPush(key, value);    }    /**     * 获取list长度     *     * @param key     * @return     */    public long getListSize(String key) {        return redisList.size(key);    }    /**     * 删除栈的值     * count> 0:删除等于从左到右移动的值的第一个元素     * count< 0:删除等于从右到左移动的值的第一个元素     * count = 0:删除等于value的所有元素     *     * @param key     * @param count     * @param value     * @return     */    public long removeList(String key, long count, String value) {        return redisList.remove(key, count, value);    }    //---------------------------------------------------------------SetOperations    /**     * 存储set     *     * @param key     * @param value     * @return     */    public long setSet(String key, String value) {        return redisSet.add(key, value);    }    /**     * 删除set     *     * @param key     * @param value     * @return     */    public long deleteSet(String key, String value) {        return redisSet.remove(key, value);    }    /**     * 获取set     *     * @param key     * @return     */    public String getSet(String key) {        return redisSet.pop(key);    }    /**     * 获取set长度     *     * @param key     * @return     */    public long getSetSize(String key) {        return redisSet.size(key);    }    //--set}

当然需要配置redis的连接词,只需要在application.properties文件里面配置就行:

#redis数据库名称  从0到15,默认为db0spring.redis.database=0#redis服务器名称spring.redis.host=192.168.80.123#redis服务器密码#spring.redis.password=123456#redis服务器连接端口号spring.redis.port=6379#redis连接池设置spring.redis.pool.max-idle=8spring.redis.pool.min-idle=0spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1#spring.redis.sentinel.master=#spring.redis.sentinel.nodes=spring.redis.timeout=60000

当然日志配置很重要,只需要新建文件logback.xml放到resources目录下就行,启动时候会自动加载:

<configuration scan="true" scanPeriod="60 seconds">    <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, -->    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">        <encoder>            <pattern>%d %p (%file:%line\)- %m%n</pattern>            <charset>GBK</charset>        </encoder>    </appender>    <appender name="baselog" class="ch.qos.logback.core.rolling.RollingFileAppender">        <File>log/base.log</File>        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">            <fileNamePattern>log/base.log.%d.%i</fileNamePattern>            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">                <!-- or whenever the file size reaches 64 MB -->                <maxFileSize>64 MB</maxFileSize>            </timeBasedFileNamingAndTriggeringPolicy>        </rollingPolicy>        <encoder>            <pattern>                %d %p (%file:%line\)- %m%n            </pattern>            <charset>UTF-8</charset> <!-- 此处设置字符集 -->        </encoder>    </appender>    <root level="INFO">        <appender-ref ref="STDOUT"/>    </root>    <logger name="cn.lijie.controller" level="INFO">        <appender-ref ref="baselog"/>    </logger></configuration>

前面准备完毕,启动MyApplication的main方法,可以在访问Controller里面的方法,但是我们需要做一些单元等等的测试,所以得编写测试用例,下面是RedisServiceImpl的测试用例.

注意:
网上是很多老版本案例,使用的是如下注解(SpringApplicationConfiguration 已经在新版本不提供了):

@RunWith(SpringJUnit4ClassRunner.class)  @SpringApplicationConfiguration(classes = Application.class)  @WebAppConfigurationpublic class xxxTest {  }

新版本的测试注解如下(MyApplication就是你那个启动main方法的类名):

@RunWith(SpringRunner.class)@SpringBootTest(classes = MyApplication.class)public class xxxTest {}

我这里的RedisServiceImpl类的方法测试用例如下:

import cn.lijie.MyApplication;import cn.lijie.service.impl.RedisServiceImpl;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;/** * User: lijie * Date: 2017/8/16 * Time: 15:08 */@RunWith(SpringRunner.class)@SpringBootTest(classes = MyApplication.class)public class RedisServiceTest {    @Autowired    RedisServiceImpl reids;    @Test    public void testRedisSet() {        reids.set("key", "value");    }    @Test    public void testRedisGey() {        System.out.println(reids.get("key"));    }    @Test    public void testRedisSetByTime() {        reids.set("key", "value", 10000L);    }    @Test    public void testRedisIncLong() {        System.out.println(reids.incLong("inc", 1));    }    @Test    public void testRedisSetHash() {        reids.setHash("hkey", "key", "value");    }    @Test    public void testRedisGetHash() {        System.out.println(reids.getHash("hkey", "key"));    }    @Test    public void testRedisGetHashByHKey() {        System.out.println(reids.getHash("hkey", "key"));    }    @Test    public void testRedisDeleteHash() {        //成功为返回1        System.out.println(reids.deleteHash("hkey", "key"));    }    @Test    public void testRedisSetLeftPush() {        reids.setLeftPush("list", "a");        reids.setLeftPush("list", "b");        reids.setLeftPush("list", "d");        reids.setLeftPush("list", "c");    }    @Test    public void testRedisgetListPopLeft() {        System.out.println(reids.getListPopLeft("list"));    }    @Test    public void testRedisSetRightPush() {        reids.setRightPush("list2", "11");        reids.setRightPush("list2", "11");        reids.setRightPush("list2", "11");        reids.setRightPush("list2", "11");    }    @Test    public void testRedisGetListPopRight() {        System.out.println(reids.getListPopRight("list2"));    }    @Test    public void testRedisGetListSize() {        System.out.println(reids.getListSize("list2"));    }    @Test    public void testRedisRemoveList() {        System.out.println(reids.removeList("list2", 0, "11"));    }    @Test    public void testRedisSetSet() {        System.out.println(reids.setSet("setKey", "setVal"));    }    @Test    public void testRedisDeleteSet() {        System.out.println(reids.deleteSet("setKey", "setVal"));    }    @Test    public void testRedisGetSet() {        System.out.println(reids.getSet("setKey"));    }    @Test    public void testRedisGetSetSize() {        System.out.println(reids.getSetSize("setKey"));    }}
原创粉丝点击