Spring Boot + Redis
启动redis
docker run --name redisServer -P -d redis
redis自带客户端,启动客户端
docker run -it --link redisServer:db --entrypoint redis-cli redis -h db
也可以使用桌面工具Redis Desktop Manager测试
下载地址:https://redisdesktop.com/download
下载完后安装,打开程序
连接服务器
可以看到上面存进去的name
新建一个Spring Boot项目,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.</modelVersion> <groupId>org.mythsky</groupId>
<artifactId>spring-boot-redis-demo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-redis-demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.</version>
</dependency> <!--<dependency>-->
<!--<groupId>springboot.db</groupId>-->
<!--<artifactId>mysql</artifactId>-->
<!--<version>${project.version}</version>-->
<!--</dependency>-->
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
添加User
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable;
import java.util.Date;
import java.util.List; public class User implements Serializable {
private Long id;
private String name;
private Date createDate;
private Department department;
private List<Role> roles; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
} public Department getDepartment() {
return department;
} public void setDepartment(Department department) {
this.department = department;
} public List<Role> getRoles() {
return roles;
} public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Department
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Department implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
Role
package org.mythsky.springbootredisdemo.domain; import java.io.Serializable; public class Role implements Serializable {
private Long id;
private String name; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
RedisConfig
package org.mythsky.springbootredisdemo.config; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; @Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory redisConnectionFactory(){
JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory();
redisConnectionFactory.setHostName("192.168.31.146");
redisConnectionFactory.setPort();
redisConnectionFactory.setUsePool(true);
return redisConnectionFactory;
}
@Bean
public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
StringRedisTemplate template=new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
UserRedis
package org.mythsky.springbootredisdemo.service; import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.mythsky.springbootredisdemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils; import java.util.List;
import java.util.concurrent.TimeUnit; @Repository
public class UserRedis {
@Autowired
private RedisTemplate<String,String> redisTemplate; public void add(String key,Long time,User user){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(user),time, TimeUnit.MINUTES);
} public void add(String key, Long time, List<User> users){
Gson gson=new Gson();
redisTemplate.opsForValue().set(key,gson.toJson(users),time, TimeUnit.MINUTES);
} public User get(String key){
Gson gson=new Gson();
User user=null;
String userJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(userJson)){
user=gson.fromJson(userJson,User.class);
}
return user;
} public List<User> getList(String key){
Gson gson=new Gson();
List<User> users=null;
String listJson=redisTemplate.opsForValue().get(key);
if(!StringUtils.isEmpty(listJson)){
users=gson.fromJson(listJson,new TypeToken<List<User>>(){}.getType());
}
return users;
} public void delete(String key){
redisTemplate.opsForValue().getOperations().delete(key);
}
}
SpringBootRedisDemoApplicationTests
package org.mythsky.springbootredisdemo; import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mythsky.springbootredisdemo.config.RedisConfig;
import org.mythsky.springbootredisdemo.domain.Department;
import org.mythsky.springbootredisdemo.domain.Role;
import org.mythsky.springbootredisdemo.domain.User;
import org.mythsky.springbootredisdemo.service.UserRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList;
import java.util.Date;
import java.util.List; @RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRedisDemoApplicationTests { private static Logger logger= LoggerFactory.getLogger(SpringBootRedisDemoApplicationTests.class);
@Autowired
UserRedis userRedis;
@Before
public void setup(){
Department department=new Department();
department.setName("开发部"); Role role=new Role();
role.setName("admin"); User user=new User();
user.setName("user");
user.setCreateDate(new Date());
user.setDepartment(department); List<Role> roles=new ArrayList<Role>();
roles.add(role); user.setRoles(roles); userRedis.delete(this.getClass().getName()+":userByName:"+user.getName());
userRedis.add(this.getClass().getName()+":userByName:"+user.getName(),10l,user);
}
@Test
public void get() {
User user=userRedis.get(this.getClass().getName()+":userByName:user");
Assert.assertNotNull(user);
logger.info("======user====== name:{}, department:{}, role:{}",user.getName(),user.getDepartment(),user.getRoles().get().getName());
} }
运行,可以在测试窗口看到结果
此时再打开桌面客户端
连接redis集群
官方文档:
最主要的是设置RedisConnectionFactory
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
config
@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class ClusterConfigurationProperties { /*
* spring.redis.cluster.nodes[0] = 127.0.0.1:7379
* spring.redis.cluster.nodes[1] = 127.0.0.1:7380
* ...
*/
List<String> nodes; /**
* Get initial collection of known cluster nodes in format {@code host:port}.
*
* @return
*/
public List<String> getNodes() {
return nodes;
} public void setNodes(List<String> nodes) {
this.nodes = nodes;
}
}
@Configuration
public class AppConfig { /**
* Type safe representation of application.properties
*/
@Autowired
ClusterConfigurationProperties clusterProperties;
@Value("${spring.redis.password}")
private String password; public @Bean
RedisConnectionFactory connectionFactory() {
RedisClusterConfiguration configuration=new RedisClusterConfiguration(clusterProperties.getNodes());
configuration.setPassword(RedisPassword.of(password));
return new JedisConnectionFactory(configuration);
}
}
配置文件
spring.redis.cluster.nodes=172.20.102.65:7001,172.20.102.65:7002,172.20.102.65:7003,172.20.102.66:7004,172.20.102.66:7005,172.20.102.66:7006
spring.redis.password=123456
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisDemoApplicationTests { @Test
public void contextLoads() {
String result= stringRedisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Test
public void test1(){
String result=redisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
System.out.println(result);
}
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String,String> redisTemplate;
}
Spring Boot + Redis的更多相关文章
- spring boot redis缓存JedisPool使用
spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...
- spring boot + redis 实现session共享
这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring se ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring boot redis 缓存(cache)集成
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- spring boot redis分布式锁
随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring b ...
- 从.Net到Java学习第四篇——spring boot+redis
从.Net到Java学习系列目录 “学习java已经十天,有时也怀念当初.net的经典,让这语言将你我相连,怀念你......”接上一篇,本篇使用到的框架redis.FastJSON. 环境准备 安装 ...
- Spring Boot Redis Cluster 实战干货
添加配置信息 spring.redis: database: 0 # Redis数据库索引(默认为0) #host: 192.168.1.8 #port: 6379 password: 123456 ...
- Spring boot redis自增编号控制 踩坑
近段期间,公司 接手一个订单号生成服务,规则的话已经由项目经理他们规定好了,主要是后面的四位数代表的关于当前订单号已经执行第几个了.而这里面有一个要求就是支持分布式.为了实现这个东西,刚开始我使用了r ...
随机推荐
- ubuntu 出现device not managed,解决方法
1. 编辑/etc/NetworkManager/NetworkManager.conf: sudo vi /etc/NetworkManager/NetworkManager.conf将其中的man ...
- php mysqli 链接数据库 CURD 增改查删
<?php function println($msg) { echo "<br>"; echo $msg; } $mysql_server_name = &qu ...
- (转)Memcache内存分配策略
转自:http://hi.baidu.com/software_one/item/0a0a6712dc7a319899ce33e0 一.Memcache内存分配机制 关于这个机制网上有很多解释的,我个 ...
- 关于Lambda
1. 查询时,包含关联子对象.如: 数据库中包含表Father和Son,映射实体如下: public class Father { public string Name{get;set;} publi ...
- (区间dp 或 记忆化搜素 )Brackets -- POJ -- 2955
http://poj.org/problem?id=2955 Description We give the following inductive definition of a “regular ...
- kepware http接口 swift
读取某变量的值 import Foundation let headers = [ "Connection": "keep-alive", "Cach ...
- MySQL查询练习(45道)
题目:设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher). 四个表的结构分别如表1-1的表(一)~表(四)所示,数据如表1 ...
- ubuntu 修改mysql 5.7数据库密码
1.vi /ect/mysql/debian 查看debain-sys-maint用户的密码 2.登录mysql 4.切换到mysql数据库,更新 user 表: update user set au ...
- AWS–Sysops notes
Monitoring, Metrics and Analysis 1.CouldWatch Introduction2.EC2 Status Troubleshooting3.Create A Cou ...
- [Proposal]Nano-Diary(纳日记)
[Motivation] 很多人都有记日记的习惯,不为别的,就为了那份情怀.但是也有很多人不记日记,原因是嫌写字麻烦.记得很久很久以前,在<读者>上读过一篇文章,大意是一个人用数值记下每天 ...