springboot集成redis

springboot与Redis


主要介绍springboot与Redis集成,内容有如下几点:

Redis安装

下载Redis的windows系统安装包,安装文件为“Redis-x64-3.2.100.msi 地址如下
—— [ Redis官网 ]

pom.xml文件加入Redis工具包

<?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>com.xmdf</groupId>
    <artifactId>proje</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>proje</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <vue.version>1.0.21</vue.version>
        <redis.version>4.0.9</redis.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</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-devtools</artifactId>
                  <optional>true</optional>
         </dependency>   
            <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
<!-- ==========================web-start========================== -->
        <dependency>  
                <groupId>org.springframework.boot</groupId>  
                <artifactId>spring-boot-starter-web</artifactId>  
         </dependency>   
<!--         web-jars -->
            <dependency>
                <groupId>org.webjars.bower</groupId>
                <artifactId>vue</artifactId>
                <version>${vue.version}</version>
            </dependency>        
<!-- ==========================web-end============================== -->
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                 </configuration>
            </plugin>
        </plugins>
    </build>
</project>

springboot与Redis的连接配置

相关配置如下所示:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database
spring.datasource.username=root
spring.datasource.password=12345678
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
server.port=8088
server.session.timeout=10
server.tomcat.uri-encoding=UTF-8

###redis-setting
# REDIS (RedisProperties)
# Redis database index -default 0
spring.redis.database=0 
# Redis host ip addr
spring.redis.host=127.0.0.1
# Redis  port
spring.redis.port=6379  
# Redis passwd
spring.redis.password=0123456789 
# redis database max pool connecting num
spring.redis.pool.max-active=8  
# redis database max pool waitting num
spring.redis.pool.max-wait=1  
# 
spring.redis.pool.max-idle=8  
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.min-idle=0 1
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=15

##Login-Path
logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR

代码实现

1.管理类实现

package com.xmdf.proje.rediscfg;
import org.springframework.cache.annotation.EnableCaching;
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.core.StringRedisTemplate;

@Configuration
@EnableCaching
public class RedisConfig {
    public static RedisTemplate<String, Object>redisTemplate;
    public static StringRedisTemplate stringRedisTemplate;

    @Bean
    public static RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        redisTemplate=new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public static StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        stringRedisTemplate=new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;

    }

}


2.服务接口

package com.xmdf.proje.rediscfg.service;

import java.util.Map;

/**
 * 
 * @author Houyer
 * @date 2018-04-24
 *  @category 获取、存入redis缓存值
 */
public interface RedisService {
    public void putRedisKeyObjectData(Map<String, Object>redisKVMap);
    public Object getRedisKeyObjectData(Map<String, String>redisVKMap);
    public void putRedisKeyStringData(Map<String, String>redisKVMap);
    public String getRedisKeyStringData(Map<String, String>redisVKMap);
}

3.服务接口实现类

package com.xmdf.proje.rediscfg.serviceimpl;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.xmdf.proje.rediscfg.RedisConfig;
import com.xmdf.proje.rediscfg.service.RedisService;

@Service
public class RedisServiceImpl implements RedisService{
    @Override
    public void putRedisKeyObjectData(Map<String, Object> redisKVMap) {
        String redisKey=(String) redisKVMap.get("key");
        Object objectData=redisKVMap.get("data");
        if (!RedisConfig.redisTemplate.hasKey(redisKey)) {
            RedisConfig.redisTemplate.opsForValue().set(redisKey, objectData);
        }
    }
    @Override
    public Object getRedisKeyObjectData(Map<String, String> redisVKMap) {
        String redisKey=redisVKMap.get("key");
        Object objData=null;
        if (RedisConfig.redisTemplate.hasKey(redisKey)) {
            objData=RedisConfig.redisTemplate.opsForValue().get(redisKey);
        }
        return objData;
    }
    @Override
    public void putRedisKeyStringData(Map<String, String> redisKVMap) {
        String redisKey=(String) redisKVMap.get("key");
        String stringData=redisKVMap.get("data");
        if (!RedisConfig.stringRedisTemplate.hasKey(redisKey)) {
            RedisConfig.stringRedisTemplate.opsForValue().set(redisKey, stringData);
        }   
    }
    @Override
    public String getRedisKeyStringData(Map<String, String> redisVKMap) {
        String redisKey=(String) redisVKMap.get("key");
        String stringData="";
        if (RedisConfig.stringRedisTemplate.hasKey(redisKey)) {
            stringData=RedisConfig.stringRedisTemplate.opsForValue().get(redisKey);
        }
        return stringData;
    }
}

4.控制层

package com.xmdf.proje.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xmdf.proje.cfgbean.User;
import com.xmdf.proje.rediscfg.service.RedisService;

@RestController
public class HelloWordController {
      @Autowired
       private JdbcTemplate jdbcTemplate;
      @Autowired
       private StringRedisTemplate stringRedisTemplate;  
      @Autowired
      RedisService redisService;
    @RequestMapping("/index")
    public String index(){
        String redisSTR="";
        ValueOperations<String, String>vopt=this.stringRedisTemplate.opsForValue();
        String key="redis_key";
        if (this.stringRedisTemplate.hasKey(key)) {
            redisSTR=vopt.get(key);
        }
        return redisSTR;
    }
    @RequestMapping("/getUser")
    public List<User> getUsers(){
        List<User>returnList=new ArrayList<User>();
        ValueOperations<String, String>vopt=this.stringRedisTemplate.opsForValue();
        User user=new User();
        String key="redis_key";
        if (this.stringRedisTemplate.hasKey(key)) {
            vopt.set(key,UUID.randomUUID().toString() );
        }
        for (int i = 0; i < 2; i++) {
            user=new User();
            user.setUserId(UUID.randomUUID().toString());
            user.setUserName(UUID.randomUUID().toString());
            user.setUserNo(UUID.randomUUID().toString());
            user.setUserSex(UUID.randomUUID().toString());
            returnList.add(user);
        }
        return returnList;
    }   
    @RequestMapping("/index_put_user")
    public boolean putTestRedis(){
        User user=new User();
        user.setUserId(UUID.randomUUID().toString());
        user.setUserName("Hello Word");
        user.setUserNo("123456");
        user.setUserSex("男");
        Map<String, Object>redisKVMap=new HashMap<>();
        redisKVMap.put("key", "user");
        redisKVMap.put("data", user);
        redisService.putRedisKeyObjectData(redisKVMap);
        return true;
    }
    @RequestMapping("/index_get_user")
    public User getTestUser() {
        Map<String, String>redisMap=new HashMap<>();
        redisMap.put("key", "user");
        User user=(User) redisService.getRedisKeyObjectData(redisMap);
        return user;
    }
}

5.User类

package com.xmdf.proje.cfgbean;
import java.io.Serializable;
@SuppressWarnings("serial")
public class User  implements Serializable{
    private String userId;
    private String userName;
    private String userNo;
    private String userSex;
    public User(String userId, String userName, String userNo, String userSex) {
        super();
        this.userId = userId;
        this.userName = userName;
        this.userNo = userNo;
        this.userSex = userSex;
    }
    public User() {
        // TODO Auto-generated constructor stub
    }
    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;
    }
    public String getUserNo() {
        return userNo;
    }
    public void setUserNo(String userNo) {
        this.userNo = userNo;
    }
    public String getUserSex() {
        return userSex;
    }
    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((userId == null) ? 0 : userId.hashCode());
        result = prime * result + ((userName == null) ? 0 : userName.hashCode());
        result = prime * result + ((userNo == null) ? 0 : userNo.hashCode());
        result = prime * result + ((userSex == null) ? 0 : userSex.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (userId == null) {
            if (other.userId != null)
                return false;
        } else if (!userId.equals(other.userId))
            return false;
        if (userName == null) {
            if (other.userName != null)
                return false;
        } else if (!userName.equals(other.userName))
            return false;
        if (userNo == null) {
            if (other.userNo != null)
                return false;
        } else if (!userNo.equals(other.userNo))
            return false;
        if (userSex == null) {
            if (other.userSex != null)
                return false;
        } else if (!userSex.equals(other.userSex))
            return false;
        return true;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "User [userId=" + userId + ", userName=" + userName + ", userNo=" + userNo + ", userSex=" + userSex
                + ", getUserId()=" + getUserId() + ", getUserName()=" + getUserName() + ", getUserNo()=" + getUserNo()
                + ", getUserSex()=" + getUserSex() + ", hashCode()=" + hashCode() + ", getClass()=" + getClass()
                + ", toString()=" + super.toString() + "]";
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值