0、pom.xml

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>

1.配置文件

#不用 springboot的redisTemplate,所以不用Springboot自身集成的redis配置
redis:
host: localhost
port:
timeout:
passpord: xiaochao
poolMaxTotal:
poolMaxIdle:
poolMaxWait:
passport: xiaochao

2.配置项映射类

package com.everjiankang.miaosha.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import lombok.Data; @Data
@Component
@ConfigurationProperties("redis")
public class RedisConfig {
private String host;
private String username;
private String passport;
private int port;
private int timeout;
private String passpord;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;
}

3.配置类

package com.everjiankang.miaosha.config;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.everjiankang.miaosha.redis.RedisConfig; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; @Configuration
public class MyConfig { @Autowired
RedisConfig redisConfig; @Bean
public JedisPool jedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
return new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout(), redisConfig.getPasspord());
}
}

4、前缀接口

package com.everjiankang.miaosha.redis;

/**
* 前缀接口
* @author guchunchao
*
*/
public interface KeyPrefix {
/**
* 获取过期时间
* @return
*/
int expireSeconds(); /**
* 获取前缀
* @return
*/
String getPrefix();
}

5、前缀基础实现

package com.everjiankang.miaosha.redis;

public abstract class BaseKeyPrefix implements KeyPrefix{

    private int expireSeconds;

    private String prefix;

    public BaseKeyPrefix(int expireSeconds, String prefix) {
super();
this.expireSeconds = expireSeconds;
this.prefix = prefix;
} public BaseKeyPrefix(String prefix) {
this.expireSeconds = 0;
this.prefix = prefix;
} @Override
public int expireSeconds() { //默认0代表永不过期
return expireSeconds;
} @Override
public String getPrefix() {
String className = getClass().getSimpleName();
return className + ":" + prefix;
}
}

6、前缀实现类

package com.everjiankang.miaosha.redis;

public class UserKey extends BaseKeyPrefix {

    private UserKey(int expireSeconds, String prefix) {
super(expireSeconds, prefix);
} private UserKey(String prefix) {
super(prefix);
} public static UserKey getById = new UserKey("id");
public static UserKey getByName = new UserKey("name"); }

7、Jedis操作Redis类:

package com.everjiankang.miaosha.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; @Service
public class RedisService { @Autowired
JedisPool jedisPool; /**
* 获取单个对象
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> T get(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
String value = jedis.get(realKey);
T t = stringToBean(value,clazz);
return t;
} finally {
returnToPool(jedis);
}
} /**
* 设置对象
* @param prefix
* @param key
* @param value
* @return
*/
public boolean set(KeyPrefix prefix, String key, Object value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = beanToString(value);
if(str == null || str.length() <=0)
return false;
int expireSecond = prefix.expireSeconds();
String realKey = prefix.getPrefix() + key;
if(expireSecond <= 0) {
jedis.set(realKey,str);
} else {
jedis.setex(realKey, expireSecond, str);
}
return true;
} finally {
returnToPool(jedis);
}
} /**
* 判断是否存在
* @param prefix
* @param key
* @return
*/
public boolean exist(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
} finally {
returnToPool(jedis);
}
} /**
* 增加
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> Long incri(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
Long incr = jedis.incr(realKey);
return incr;
} finally {
returnToPool(jedis);
}
} /**
* 减少
* @param prefix
* @param key
* @param clazz
* @return
*/
public <T> Long decr(KeyPrefix prefix,String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String realKey = prefix.getPrefix() + key;
Long decr = jedis.decr(realKey);
return decr;
} finally {
returnToPool(jedis);
}
} /**
* Java对象转String
* @param value
* @return
*/
private <T> String beanToString(T value) {
if(value == null)
return null;
Class<?> clazz = value.getClass(); if(clazz == int.class || clazz == Integer.class
|| clazz == long.class || clazz == Long.class
|| clazz == float.class || clazz == Float.class
|| clazz == double.class || clazz == Double.class
)
return "" + value;
else if(value instanceof String)
return (String) value;
else
return JSON.toJSONString(value); } /**
* string 转Java
* @param value
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
private <T> T stringToBean(String value,Class<T> clazz) {
if(value == null)
return null;
if(clazz == int.class || clazz == Integer.class)
return (T) Integer.valueOf(value);
else if( clazz == long.class || clazz == Long.class)
return (T) Long.valueOf(value);
else if(clazz == float.class || clazz == Float.class)
return (T) Float.valueOf(value);
else if(clazz == double.class || clazz == Double.class)
return (T) Double.valueOf(value);
else if(value instanceof String)
return (T) value;
else
return JSON.toJavaObject(JSON.parseObject(value), clazz);
} /**
* 将Jedis链接还回连接池:详情close方法
* @param jedis
*/
private void returnToPool(Jedis jedis) {
if(jedis != null)
jedis.close();
}
}

8、controller调用实例

package com.everjiankang.miaosha.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.everjiankang.miaosha.model.CodeMsg;
import com.everjiankang.miaosha.model.Result;
import com.everjiankang.miaosha.model.User;
import com.everjiankang.miaosha.redis.RedisService;
import com.everjiankang.miaosha.redis.UserKey;
import com.everjiankang.miaosha.service.UserService; @Controller
@RequestMapping("/test")
public class TestController { @Autowired
UserService userService; @Autowired
RedisService redisService; @PostMapping("/test01")
@ResponseBody
public Result<String> test01() {
return Result.success("hello world");
} @PostMapping("/helloError")
@ResponseBody
public Result<String> helloError() {
return Result.error(CodeMsg.SERVER_ERROR);
} @RequestMapping("/thymeleaf")
public String thymeleaf() {
return "thymeleaf";
} @RequestMapping("/getById/{id}")
@ResponseBody
public Result<User> getById(@PathVariable("id") int id) {
return Result.success(userService.selectByPrimaryKey(id));
} @RequestMapping("/redisGet/{key}")
@ResponseBody
public Result<String> redisGet(@PathVariable("key") String key) {
String string = redisService.get(UserKey.getById,key, String.class);
return Result.success(string);
} @RequestMapping("/redisSet/{key}/{value}")
@ResponseBody
public Result<String> redisSet(@PathVariable("key") String key,@PathVariable("value") String value) {
if(key != null && !"".equals(key.trim()) && value != null && !"".equals(value)) {
boolean result = redisService.set(UserKey.getById,key, value);
if(result)
return Result.success(redisService.get(UserKey.getById,key, String.class));
else
return Result.error(CodeMsg.SERVER_ERROR);
} else {
return Result.error(CodeMsg.SERVER_ERROR);
}
} @RequestMapping("/redisSetUserTest")
@ResponseBody
public Result<User> redisSetUserTest(@PathVariable("key") String key) {
User user = new User();
user.setId(1);
user.setAge(27);
user.setName("xiaochao");
user.setSex(1);
boolean result = redisService.set(UserKey.getById,key, user);
if(result)
return Result.success(user);
else
return Result.error(CodeMsg.SERVER_ERROR);
} @RequestMapping("/redisSetUserTest")
@ResponseBody
public Result<User> redisGetUserTest(@PathVariable("id") String id) { User user = redisService.get(UserKey.getById,id,User.class);
if(user != null)
return Result.success(user);
else
return Result.error(CodeMsg.SERVER_ERROR);
} }

33. Springboot 系列 原生方式引入Redis,非RedisTemplate的更多相关文章

  1. 实例讲解Springboot以Template方式整合Redis及序列化问题

    1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...

  2. 实例讲解Springboot以Repository方式整合Redis

    1 简介 Redis是高性能的NoSQL数据库,经常作为缓存流行于各大互联网架构中.本文将介绍如何在Springboot中整合Spring Data Redis,使用Repository的方式操作. ...

  3. springBoot系列教程03:redis的集成及使用

    1.为了高可用,先安装redis集群 参考我的另一篇文章 http://www.cnblogs.com/xiaochangwei/p/7993065.html 2.POM中引入redis <de ...

  4. SpringBoot使用注解方式整合Redis

    1.首先导入使用Maven导入jar包 <dependency> <groupId>org.springframework.boot</groupId> <a ...

  5. SpringBoot系列-整合Mybatis(注解方式)

    目录 一.常用注解说明 二.实战 三.测试 四.注意事项 上一篇文章<SpringBoot系列-整合Mybatis(XML配置方式)>介绍了XML配置方式整合的过程,本文介绍下Spring ...

  6. SpringBoot系列之Spring容器添加组件方式

    SpringBoot系列之Spring容器添加组件方式 本博客介绍SpringBoot项目中将组件添加到Spring容器中的方法,SpringBoot项目有一个很明显的优点,就是不需要再编写xml配置 ...

  7. SpringBoot系列教程之Redis集群环境配置

    之前介绍的几篇redis的博文都是基于单机的redis基础上进行演示说明的,然而在实际的生产环境中,使用redis集群的可能性应该是大于单机版的redis的,那么集群的redis如何操作呢?它的配置和 ...

  8. SpringBoot系列(十四)集成邮件发送服务及邮件发送的几种方式

    往期推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件详解 SpringBoot系列(四)web静 ...

  9. Java Redis系列1 关系型数据库与非关系型数据库的优缺点及概念

    Java Redis系列1 关系型数据库与非关系型数据库的优缺点及概念 在学习redis之前我们先来学习两个概念,即什么是关系型数据库什么是非关系型数据库,二者的区别是什么,二者的关系又是什么? ** ...

随机推荐

  1. vue SSR : 原理(一)

    前言: 由于vue 单页面对seo搜索引擎不支持,vue官网给了一个解决方案是ssr服务端渲染来解决seo这个问题,最近看了很多关于ssr的文章, 决定总结下: 参考博客:从0开始,搭建Vue2.0的 ...

  2. Cocos2d-x游戏开发之lua编辑器 Sublime 搭建,集成cocos2dLuaApi和自有类

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/wisdom605768292/article/details/34085969 Sublime Te ...

  3. JavaScript代码组织结构良好的5个特点

    JavaScript代码组织结构良好的5个特点,随着JavaScript项目的成长,如果你不小心处理的话,他们往往会变得难以管理.我们发现自己常常陷入的一些问题: 当在创建新的页面时发现,很难重用或测 ...

  4. 关于Eclipse的版本、分支、衍生版本

    Eclipse 简介: Eclipse的历史: Eclipse的发布版本: Eclipse分支: 关于不同分支版本的区别,点击链接: http://www.eclipse.org/downloads/ ...

  5. SpringCloud(3)服务消费者(Feign)

    上一篇文章,讲述了如何通过 RestTemplate+Ribbon 去消费服务,这篇文章主要讲述如何通过Feign去消费服务. 1.Feign简介 Feign是一个声明式的伪Http客户端,它使得写H ...

  6. 多项目管理中PMO的作用

    随着现代企业规模的不断扩大,多项目同时运行成为了现代企业的常态,以及企业项目化进程的不断深入,大部分企业不再仅仅只运行一个项目,而且数量之大已经超出了人们的想象,如惠普公司每年有3000个左右的项目, ...

  7. JQuery 获取select 的value值和文本值

    <select name="month" id="selMonth">    <option value="1">一 ...

  8. hdu-1728(贪心&&bfs的灵活运用吧)

    链接 [https://vjudge.net/contest/256476#problem/D] 题意 给定一个m × n (m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到 ...

  9. java基础-不用ide如何打包

    java基础-不用ide如何打包 1. 建立目录 src存放源文件 classes存放编译文件 2. 建立类文件 主类 package test.ant; import test.ant.MyTool ...

  10. OracleSql语句学习(五)

    --数据库对象数据库对象包含:表,视图,索引,序列视图VIEN视图在SQL语句中体现的角色与表一样,但是视图并非真实存在的表,它只是对应一条查询语句的结果集 使用视图通常是为了重用子查询,简化SQL语 ...