springboot 使用redis
2018-03-08 10:57
344 查看
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化。
@Component
public class RedisUtility {
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value,expireTime,TimeUnit.SECONDS);
//redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
使用注解缓存的方式:
使用演示
Java代码
package com.wisely.ij.service;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created by wisely on 2015/5/25.
*/
@Service
public class DemoService {
@Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
public User findUser(Long id,String firstName,String lastName){
System.out.println("无缓存的时候调用这里");
return new User(id,firstName,lastName);
}
@Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
public Address findAddress(Long id,String province,String city){
System.out.println("无缓存的时候调用这里");
return new Address(id,province,city);
}
}
Java代码
package com.wisely.ij.web;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import com.wisely.ij.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by wisely on 2015/5/25.
*/
@Controller
public class DemoController {
@Autowired
DemoService demoService;
@RequestMapping("/test")
@ResponseBody
public String putCache(){
demoService.findUser(1l,"wang","yunfei");
demoService.findAddress(1l,"anhui","hefei");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return "ok";
}
@RequestMapping("/test2")
@ResponseBody
public String testCache(){
User user = demoService.findUser(1l,"wang","yunfei");
Address address =demoService.findAddress(1l,"anhui","hefei");
System.out.println("我这里没执行查询");
System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
return "ok";
}
}
redis介绍
Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍Redis在Spring Boot中两个典型的应用场景。如何使用
1、引入 spring-boot-starter-redis<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>2、添加配置文件
# REDIS (RedisProperties) # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=192.168.0.58 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=03、添加cache的配置类
@Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport{ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 //rcm.setDefaultExpiration(60);//秒 return rcm; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }4、好了,接下来就可以直接使用了
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class TestRedis { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void test() throws Exception { stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); } @Test public void testObj() throws Exception { User user=new User("aa@126.com", "aa", "aa123456", "aa","123"); ValueOperations<String, User> operations=redisTemplate.opsForValue(); operations.set("com.neox", user); operations.set("com.neo.f", user,1,TimeUnit.SECONDS); Thread.sleep(1000); //redisTemplate.delete("com.neo.f"); boolean exists=redisTemplate.hasKey("com.neo.f"); if(exists){ System.out.println("exists is true"); }else{ System.out.println("exists is false"); } // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName()); } }5. 写了util 来操作,使用@Component 在其他代码中可以@Autowire 来直接使用
@Component
public class RedisUtility {
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value,expireTime,TimeUnit.SECONDS);
//redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
使用注解缓存的方式:
使用演示
Java代码
package com.wisely.ij.service;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* Created by wisely on 2015/5/25.
*/
@Service
public class DemoService {
@Cacheable(value = "usercache",keyGenerator = "wiselyKeyGenerator")
public User findUser(Long id,String firstName,String lastName){
System.out.println("无缓存的时候调用这里");
return new User(id,firstName,lastName);
}
@Cacheable(value = "addresscache",keyGenerator = "wiselyKeyGenerator")
public Address findAddress(Long id,String province,String city){
System.out.println("无缓存的时候调用这里");
return new Address(id,province,city);
}
}
Java代码
package com.wisely.ij.web;
import com.wisely.ij.domain.Address;
import com.wisely.ij.domain.User;
import com.wisely.ij.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by wisely on 2015/5/25.
*/
@Controller
public class DemoController {
@Autowired
DemoService demoService;
@RequestMapping("/test")
@ResponseBody
public String putCache(){
demoService.findUser(1l,"wang","yunfei");
demoService.findAddress(1l,"anhui","hefei");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return "ok";
}
@RequestMapping("/test2")
@ResponseBody
public String testCache(){
User user = demoService.findUser(1l,"wang","yunfei");
Address address =demoService.findAddress(1l,"anhui","hefei");
System.out.println("我这里没执行查询");
System.out.println("user:"+"/"+user.getFirstName()+"/"+user.getLastName());
System.out.println("address:"+"/"+address.getProvince()+"/"+address.getCity());
return "ok";
}
}
相关文章推荐
- Spring Boot系列(七)Spring Boot使用Redis实现session共享
- Spring Boot中使用Redis数据库
- spring boot(三):Spring Boot中Redis的使用
- springboot使用protostuff进行序列化和反序列化整合redis的redisTemplate的各种方法的写法
- redis中的基本数据类型,以及在Spring-Boot对Redis的基本使用
- 4 Springboot中使用redis存储集合数据,并模拟条件查询、分页读取
- Spring Boot使用redis做数据缓存
- Redis系列三 - Spring boot如何使用redis做缓存及缓存注解的用法总结
- 使用springboot+redis实现session共享
- Spring boot redis的使用(一)
- 使用Java(Springboot)操作Redis
- 使用Java(Springboot)操作Redis
- Spring Boot教程(三十三)使用Redis数据库(1)
- Spring Boot使用redis做数据缓存
- (十九)SpringBoot之使用Spring Session集群-redis
- Spring boot下配置使用redis--template编码形式
- Spring-boot通过redisTemplate使用redis(无须手动序列化)
- REDIS学习(3.2)spring boot 使用redis作为缓存
- Spring Boot使用Redis如何实现Session共享
- spring boot使用redisTemplate存储键值出现乱码