Spring Boot(三)——Redis

来源:互联网 发布:grub引导修复 ubuntu 编辑:程序博客网 时间:2024/06/14 22:32
Spring Boot 学习笔记:                          

Spring Boot(一)——入门环境搭建      Spring Boot(二)——MyBatis             Spring Boot(三)——Redis  
Spring Boot(四)——Mongodb          Spring Boot(五)——RabbitMQ         Spring Boot(六)——Spring Data Jpa

GitHub地址:

https://github.com/lyhkmm/SpringBoot

一、Redis介绍

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型

二、使用配置

1、引入 spring-boot-starter-redis,SpringBoot从1.4版本开始,spring-boot-starter-redis依赖改名了。

<!--支持Redis的模块--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>1.5.2.RELEASE</version></dependency>

2、添加Redis配置文件,在resources\application.properties配置文件中添加

# Redis数据库索引(默认为0)spring.redis.database=0# Redis服务器地址spring.redis.host=127.0.0.1# 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=0

3、添加配置类RedisConf:

package com.lyh.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import java.lang.reflect.Method;@Configuration@EnableCachingpublic class RedisConf 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);        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、创建User实体对象:

package com.lyh.demo.entity;public class User {    private Long id;    private String userName;    private String passWord;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassWord() {        return passWord;    }    public void setPassWord(String passWord) {        this.passWord = passWord;    }    public User() { }    public User(Long id, String userName, String passWord) {        this.id = id;        this.userName = userName;        this.passWord = passWord;    }    @Override    public String toString() {        return "User{" +                "id=" + id +                ", userName='" + userName + '\'' +                ", passWord='" + passWord + '\'' +                '}';    }}

5、使用Redis,在HelloController添加两个方法:setRedis()和getRedis()

package com.lyh.demo.controller;import com.lyh.demo.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController//@RestController的意思就是controller里面的方法都以json格式输出,不用再写什么jackjson配置的了!public class HelloWorldController {    @Autowired    private StringRedisTemplate stringRedisTemplate;    @Autowired    private RedisTemplate redisTemplate;    @RequestMapping("/setRedis")    public String setRedis(){        ValueOperations<String,String> valueOperationsStrRedis=stringRedisTemplate.opsForValue();        ValueOperations<String,Object> valueOperationsRedis=redisTemplate.opsForValue();        valueOperationsStrRedis.set("info","你好!");        User user=new User(System.currentTimeMillis(),"lyh","123456");        valueOperationsRedis.set("user",user);        return "success";    }    @RequestMapping("/getRedis")    public String getRedis(){        ValueOperations<String,String> valueOperationsStrRedis=stringRedisTemplate.opsForValue();        ValueOperations<String,Object> valueOperationsRedis=redisTemplate.opsForValue();        String info=valueOperationsStrRedis.get("info");        User user=(User) valueOperationsRedis.get("user");        return info+user.toString();    }}

关于StringRedisTemplate 和RedisTemplate的区别:
StringRedisTemplate :当你的redis数据库里面本来存的是字符串数据或者你要存取的数据就是字符串类型数据的时候,那么你就使用StringRedisTemplate即可。
RedisTemplate:但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用RedisTemplate是更好的选择。

三、通过浏览器访问测试:



下一章:Spring Boot(四)——Mongodb  GitHub案例地址:SpringBoot+Redis

阅读全文
1 0
原创粉丝点击