新手入门:SpringBoot整合单节点Redis

                                              SpringBoot整合单节点Redis

       本人近段时间开始接触Redis,也由eclipse转战IDEA,根据所学所想整理一篇文章,为想要学习Redis的同学提供一点参考资料,如果能帮助他人那是最好哒~

       另外,本文只介绍了SpringBoot整合单点Redis流程,没有介绍Redis的安装及使用,接下来会另写一篇文章介绍。

一、创建项目

1、双击打开IDEA,进入欢迎页,如下图:

2、点击上图中的“+ Create New Project”,在弹出的对话框中选择底部的“Empty Project”,然后点击“Next”按钮;

3、填写“Project name”及“Porject locations”,如图我设置项目名为Test,路径为D:\source\Test,然后点击“Finish”按钮;

注意:虽然有其他博主介绍过,这里还是强调一下,这个软件中的Project不是eclipse中的Project项目,而是eclipse中的工作空间workspace(也有的人说类似eclipse中的working set),而该软件中的Module才是eclipse中的Project项目,所以新建Project是新建workspace,而新建Module才是新建Project项目。

4、此时会弹出新建Module的对话框,点击图中1处的“+”后会出现一个下拉菜单,选择“New Module”,然后配置Module,按顺序执行2、3、4、5

注意:

(1)IDEA配置JDK的文章很多,请自行百度,谢谢;

(2)本文演示的是Springboot整合redis,因此需要使用maven,IDEA配置maven的文章也很多,请自行百度,谢谢。

5、如图1、2处填写项目坐标GroupId、ArtifactId,查看3处,点击4处“Next”继续;

6、按照下图依次点击1、2、3继续

7、查看“Module name”、“Content root”及“Module file location”,点击“Finish”继续;

8、继续点击“OK”即可。

9、以下是创建好项目的界面,就可以开始动手编码了。

二、修改配置文件

1、pom.xml文件

打开pom.xml文件,添加以下依赖:

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-pool2</artifactId>

    <version>2.4.2</version>

</dependency>

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-redis</artifactId>

    <version>2.0.3.RELEASE</version>

</dependency>

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-lang3</artifactId>

    <version>3.2</version>

</dependency>

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>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cxg.test</groupId>
    <artifactId>redistest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redistest</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!--指定maven编译jdk-->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、application.properties文件

打开application.properties属性文件添加redis配置

#项目配置
server.port=8080
spring.application.name=redistest

#redis配置
spring.redis.database=0
spring.redis.host=192.168.198.132  #Redis服务器地址
spring.redis.port=6380  #Redis服务器开放的端口
spring.redis.password=
spring.redis.timeout=10000ms
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

三、编写代码

项目的目录结构如下:

RedisConfig代码如下:

package com.cxg.test.redistest.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
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;

/**
 * Redis配置类
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * log
     */
    private static final Logger logger = LogManager.getLogger(RedisConfig.class);

    /**
     * 配置自定义redisTemplate
     * @return
     */
    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        logger.debug("start to config redisTemplate.");

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();

        logger.debug("Config redisTemplate end.");
        return template;
    }
}

 IRedisHashService代码如下:

package com.cxg.test.redistest.service;

/**
 * 处理Redis缓存数据的业务接口
 *
 * @author cxg
 * @date 20181228 14:21:54
 * @modify 20181228 cxg v1.0 创建
 * @since v1.0
 */
public interface IRedisHashService {

    /**
     * HashMap中的是否存在键值为key的hash结构
     *
     * @param key 键值
     * @return 返回 存在true,不存在false
     * @author cxg
     * @date 20181228 14:23:37
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    Boolean hasKey(String key);

    /**
     * 根据给定键值key,获取Hash结构中的key为name对应的value.
     *
     * @param key 键值
     * @param name Hash结构中的key值
     * @return 返回 Hash结构中的key值为name对应的value
     * @author cxg
     * @date 20181228 14:22:38
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    String getRedisHash(String key, String name);

    /**
     * 向指定键值key中新增一个Hash结构键值对,key为name,value为value
     *
     * @param key 键值
     * @param name Hash结构中的键
     * @param value Hash结构中的键对应的值
     * @author cxg
     * @date 20181228 14:22:38
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    void addRedisHash(String key, String name, String value);

    /**
     * 删除Redis中键值为key的hash结构
     *
     * @param key 键值
     * @return 返回 boolean 删除结果,成功true,失败false
     * @author cxg
     * @date 20181228 14:52:14
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    Boolean delRedisHash(String key);
}

RedisHashServiceImpl代码如下:

package com.cxg.test.redistest.service.impl;

import com.cxg.test.redistest.service.IRedisHashService;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 处理Redis缓存数据的业务逻辑
 */
@Service("redisHashService")
public class RedisHashServiceImpl implements IRedisHashService {

    /**
     * log
     */
    private static final Logger logger = LogManager.getLogger(RedisHashServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * HashMap中的是否存在键值为key的hash结构
     *
     * @param key 键值
     * @return 返回 存在true,不存在false
     * @author cxg
     * @date 20181228 14:23:37
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    @Override
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 根据给定键值key,获取Hash结构中的key为name对应的value.
     *
     * @param key 键值
     * @param name Hash结构中的key值
     * @return 返回 Hash结构中的key值为name对应的value
     * @author cxg
     * @date 20181228 14:22:38
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    @Override
    public String getRedisHash(String key, String name) {
        return redisTemplate.opsForHash().get(key, name).toString();
    }

    /**
     * 向指定键值key中新增一个Hash结构键值对,key为name,value为value
     *
     * @param key 键值
     * @param name Hash结构中的键
     * @param value Hash结构中的键对应的值
     * @author cxg
     * @date 20181228 14:22:38
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    @Override
    public void addRedisHash(String key, String name, String value) {
        redisTemplate.opsForHash().put(key, name,value);
    }

    /**
     * 删除Redis中键值为key的hash结构
     *
     * @param key 键值
     * @return 返回 boolean 删除结果,成功true,失败false
     * @author cxg
     * @date 20181228 14:52:14
     * @modify 20181228 cxg v1.0 创建
     * @since v1.0
     */
    @Override
    public Boolean delRedisHash(String key) {
        return redisTemplate.delete(key);
    }
}

TestController测试类代码如下:

package com.cxg.test.redistest.controller;

import com.cxg.test.redistest.service.IRedisHashService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testController")
public class TestController {

    @Autowired
    private IRedisHashService redisHashService;

    @RequestMapping("/getModel")
    @ResponseBody
    public String getModel() {

        boolean key = redisHashService.hasKey("1");
        if (key) {
            System.out.println("存在key");
            String age = redisHashService.getRedisHash("1", "张三");
            System.out.println("age:" + age);
        } else {
            System.out.println("不存在,将添加数据。");
            redisHashService.addRedisHash("1", "张三", "16");
            System.out.println("数据添加成功,请重新访问。");
        }
        return "success";
    }

    @RequestMapping("/delModel")
    @ResponseBody
    public String delModel(){
        boolean key = redisHashService.hasKey("1");
        if (key) {
            Boolean flag=redisHashService.delRedisHash("1");
            if(flag){
                System.out.println("删除成功");
            }else {
                System.out.println("删除失败,请重试");
            }
        }
        return "success";
    }
}

四、测试结果

1、启动程序

2、在地址栏输入地址:http://localhost:8080/testController/getModel

3、日志打印:

4、远程访问Redis服务器,输入命令:hgetall 1,则:

5、再次访问地址:http://localhost:8080/testController/getModel

6、在地址栏输入地址:http://localhost:8080/testController/delModel

7、远程访问Redis服务器,输入命令:hgetall 1,则:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值