详细集成Redis (一)
1.添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.</version>
</dependency>
2.在application.properties中配置redis
#redis
redis.host=192.168.220.128
redis.port=
redis.timeout=
redis.password=
redis.poolMaxTotal=
redis.poolMaxIdle=
redis.poolMaxWait=
3.创建RedisConfig类 对应application.properties中的配置
@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig {
private String host;
private int port;
private int timeout;//秒
private String password;
private int poolMaxTotal;
private int poolMaxIdle;
private int poolMaxWait;//秒
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPoolMaxTotal() {
return poolMaxTotal;
}
public void setPoolMaxTotal(int poolMaxTotal) {
this.poolMaxTotal = poolMaxTotal;
}
public int getPoolMaxIdle() {
return poolMaxIdle;
}
public void setPoolMaxIdle(int poolMaxIdle) {
this.poolMaxIdle = poolMaxIdle;
}
public int getPoolMaxWait() {
return poolMaxWait;
}
public void setPoolMaxWait(int poolMaxWait) {
this.poolMaxWait = poolMaxWait;
}
}
4.创建RedisServer
@Service
public class RedisService { @Autowired
JedisPool jedisPool; /**
* 获取当个对象
* */
public <T> T get(KeyPrefix prefix, String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
String str = jedis.get(realKey);
T t = stringToBean(str, clazz);
return t;
}finally {
returnToPool(jedis);
}
} /**
* 设置对象
* */
public <T> boolean set(KeyPrefix prefix, String key, T value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String str = beanToString(value);
if(str == null || str.length() <= ) {
return false;
}
//生成真正的key
String realKey = prefix.getPrefix() + key;
int seconds = prefix.expireSeconds();
if(seconds <= ) {
jedis.set(realKey, str);
}else {
jedis.setex(realKey, seconds, str);
}
return true;
}finally {
returnToPool(jedis);
}
} /**
* 判断key是否存在
* */
public <T> boolean exists(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.exists(realKey);
}finally {
returnToPool(jedis);
}
} /**
* 增加值
* */
public <T> Long incr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.incr(realKey);
}finally {
returnToPool(jedis);
}
} /**
* 减少值
* */
public <T> Long decr(KeyPrefix prefix, String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
//生成真正的key
String realKey = prefix.getPrefix() + key;
return jedis.decr(realKey);
}finally {
returnToPool(jedis);
}
} private <T> String beanToString(T value) {
if(value == null) {
return null;
}
Class<?> clazz = value.getClass();
if(clazz == int.class || clazz == Integer.class) {
return ""+value;
}else if(clazz == String.class) {
return (String)value;
}else if(clazz == long.class || clazz == Long.class) {
return ""+value;
}else {
return JSON.toJSONString(value);
}
} @SuppressWarnings("unchecked")
private <T> T stringToBean(String str, Class<T> clazz) {
if(str == null || str.length() <= || clazz == null) {
return null;
}
if(clazz == int.class || clazz == Integer.class) {
return (T)Integer.valueOf(str);
}else if(clazz == String.class) {
return (T)str;
}else if(clazz == long.class || clazz == Long.class) {
return (T)Long.valueOf(str);
}else {
return JSON.toJavaObject(JSON.parseObject(str), clazz);
}
} private void returnToPool(Jedis jedis) {
if(jedis != null) {
jedis.close();
}
} }
5.创建RedisPoolFactory
@Service
public class RedisPoolFactory { @Autowired
RedisConfig redisConfig; @Bean
public JedisPool JedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * );
JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
redisConfig.getTimeout()*, redisConfig.getPassword(), );
return jp;
} }
6.在controller中写一个demo
@Controller
@RequestMapping("/demo")
public class SampleController { @Autowired
UserService userService; @Autowired
RedisService redisService; @RequestMapping("/hello")
@ResponseBody
public Result<String> home() {
return Result.success("Hello,world");
} @RequestMapping("/error")
@ResponseBody
public Result<String> error() {
return Result.error(CodeMsg.SESSION_ERROR);
} @RequestMapping("/hello/themaleaf")
public String themaleaf(Model model) {
model.addAttribute("name", "Joshua");
return "hello";
} @RequestMapping("/db/get")
@ResponseBody
public Result<User> dbGet() {
User user = userService.getById();
return Result.success(user);
} @RequestMapping("/db/tx")
@ResponseBody
public Result<Boolean> dbTx() {
userService.tx();
return Result.success(true);
} @RequestMapping("/redis/get")
@ResponseBody
public Result<User> redisGet() {
User user = redisService.get(UserKey.getById, ""+, User.class);
return Result.success(user);
} @RequestMapping("/redis/set")
@ResponseBody
public Result<Boolean> redisSet() {
User user = new User();
user.setId();
user.setName("");
redisService.set(UserKey.getById, ""+, user);//UserKey:id1
return Result.success(true);
} }
详细集成Redis (一)的更多相关文章
- 详细介绍Redis的几种数据结构以及使用注意事项(转)
原文:详细介绍Redis的几种数据结构以及使用注意事项 1. Overview 1.1 资料 <The Little Redis Book>,最好的入门小册子,可以先于一切文档之前看,免费 ...
- (35)Spring Boot集成Redis实现缓存机制【从零开始学Spring Boot】
[本文章是否对你有用以及是否有好的建议,请留言] 本文章牵涉到的技术点比较多:Spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对 ...
- 7、Spring Boot 2.x 集成 Redis
1.7 Spring Boot 2.x 集成 Redis 简介 继续上篇的MyBatis操作,详细介绍在Spring Boot中使用RedisCacheManager作为缓存管理器,集成业务于一体. ...
- Spring Boot从入门到精通(六)集成Redis实现缓存机制
Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言 ...
- Spring Boot 如何快速集成 Redis 哨兵?
上一篇:Spring Boot 如何快速集成 Redis? 前面的分享栈长介绍了如何使用 Spring Boot 快速集成 Redis,上一篇是单机版,也有粉丝留言说有没有 Redis Sentine ...
- Spring Boot集成Redis集群(Cluster模式)
目录 集成jedis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 集成spring-data-redis 引入依赖 配置绑定 注册 获取redis客户端 使用 验证 异常处理 同样的, ...
- 【springBoot】springBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- SpringBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- spring集成redis
redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快.常用作缓存和发布-订阅式的消息队列.redis官方没有提供windows版本的软件.windows版本 ...
随机推荐
- selenium+Headless Chrome实现不弹出浏览器自动化登录
目前由于phantomjs已经不维护了,而新版的Chrome(59+)推出了Headless模式,对爬虫来说尤其是定时任务的爬虫截屏之类的是一大好事. 不过按照网络上的一些方法来写的话,会报下面的错误 ...
- java 枚举使用教程
转载:https://blog.csdn.net/newbie_907486852/article/details/81027512 一.枚举型常量 首先枚举是一个特殊的class,这个class相当 ...
- 关于两栏布局,三栏布局,一级点击三角触发select的onchange事件问题
首先看这样一个效果:,这个截图来自移动端的列表的一整行,在这个效果当中,存在两个技术点,首先选择祝福卡这个宽度是一定的,右边的部分,宽度随着手机屏幕的宽度而自适应,再一个技术点就是点击最右侧向下箭头, ...
- 禁止root登陆sshd/并修改默认端口号
1,新建一个用户: #useradd xxx 2,为新用户设置密码: #passwd xxx 3,修改sshd配置文件 #vi /etc/ssh/sshd_config 查找“#PermitRootL ...
- 1.1 Django起步
1.1 Django起步 1.1.1. Django简介 Django开发框架(简称Django)诞生的时间是2003年的金秋时节,美国有两位程序员Adrian Holovaty和Simon ...
- Lab 11-1
Analyze the malware found in Lab11-01.exe. Questions and Short Answers What does the malware drop to ...
- Lab 10-3
This lab includes a driver and an executable. You can run the executable from anywhere, but in order ...
- 8.2 GOF设计模式一: 单实例模式 SingleTon
GOF设计模式一: 单实例模式 SingleTon 整个美国,只有一个“现任美国总统” 比如,在学校,“老师”,有数百个:“校长”,只有一个 系统运行时,如何保证某个类只允许实例化一个对象 ...
- .net邮件发送帮助类
代码如下: using System; using System.Collections.Generic; using System.Text; using System.Configuration; ...
- Myeclipse和idea对比
新入的公司要用myeclipse,没办法,只能跟着队伍走.(myeclipse以下简写为me) 1.myeclipse的快捷键并不能设置鼠标滚轮之类的,之前在idea上配置滚轮下滚展开package, ...