SpringBoot-Redis

SpringBoot整合

java代码操作Redis ,需要使用Jedis,也就是redis支持java的第三方类库

注意:Jedis2.7以上的版本才支持集群操作

maven 配置

新建SpringBoot2.0以上的WEB工程在pom.xml文件中加

org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2

配置文件配置

spring:
  redis:
    port: 6379
    password: rzkruizhukai123.
    host: 47.***
    lettuce:
      pool:
        max-active: 10  #最大连接数
        max-idle: 6     #最大空闲数
        min-idle: 2     #最小空闲数
        max-wait: 1000
    timeout: 2000       #连接

RedisConfig

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

/**
 * fileName:RedisConfig
 * description:
 * author:rzk
 * createTime:2020/6/28 10:05
 * versioni:1.0.0
 */
@Configuration
public class RedisConfig {

    //自己定义一个RedisTemplate
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
            throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);

        //Json序列化配置
        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);
        //String  的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        //hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();

        return template;
    }
}

实体类User

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable{
    private String id;
    private String name;
    private Integer age;
}

UserServiceImpl

import com.rzk.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * fileName:UserServiceImpl
 * description:
 * author:rzk
 * createTime:2020/7/17 9:36
 * versioni:1.0.0
 */
@Service
@Slf4j
public class UserServiceImpl {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    /**
     * Redis String 类型
     * 需求: 用户输入一个 key
     * 先判断Redis中是否存在该数据
     *
     * 如果存在,在Redis中进行查询,并返回
     * 如果不存在,在MySQL数据库查询,将结果赋给Redis,并返回
     */

    public String getString(String key){
        System.out.println(redisTemplate);
        return null;
    }

测试-->整合完成

@SpringBootTest
class SpringbootLuttuceApplicationTests {   
	@Autowired
    private UserServiceImpl userService;
    @Test
    void contextLoads() {
        userService.getString("aaa");
    }
}

使用RedisTemplate操作String类型

### UserServiceImpl


import com.rzk.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


/**
 * fileName:UserServiceImpl
 * description:
 * author:rzk
 * createTime:2020/7/17 9:36
 * versioni:1.0.0
 */
@Service
@Slf4j
public class UserServiceImpl {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    /**
     * Redis String 类型
     * 需求: 用户输入一个 key
     * 先判断Redis中是否存在该数据
     *
     * 如果存在,在Redis中进行查询,并返回
     * 如果不存在,在MySQL数据库查询,将结果赋给Redis,并返回
     */

    public String getString(String key){
        if (redisTemplate.hasKey(key)){
            log.info("-------------->Redis中查询出来:");
            return (String) redisTemplate.opsForValue().get(key);
        }else{
            String val="RedisTemplate模板学习lettuce客户端";
            log.info("MySQL中查询出来"+val);
            redisTemplate.opsForValue().set(key,val);
            log.info("-------------->在MySQL中查询出来的结果存入Redis中");
            return  val;
        }
    }

    /**
     * 测试String类型
     *
     *需求:用户输入一个redis数据,该key的有效期为28小时
     */
    public void expireStr(String key,String value){
        redisTemplate.opsForValue().set(key,value);//存进去
        redisTemplate.expire(key,28, TimeUnit.HOURS);
    }

测试

@SpringBootTest
class SpringbootLuttuceApplicationTests {
    @Autowired
    private UserServiceImpl userService;

    @Test
    void T1() {
        String rzk = userService.getString("rzk");
        System.out.println(rzk);
    }
}

第一次查询

第二次就会从redis查询

使用key的有效期为28小时

UserServiceImpl


    /**
     * 测试String类型
     *
     *需求:用户输入一个redis数据,该key的有效期为28小时
     */
    public void expireStr(String key,String value){
        redisTemplate.opsForValue().set(key,value);//存进去
        redisTemplate.expire(key,28, TimeUnit.HOURS);
    }

使用Hash

UserServiceImpl


    /**
     * 测试Hash类型演示
     * @param id
     * @return
     * 根据Id查询用户对象信息
     * 先判断Redis中是否存在该key
     * 如果不存在,查询数据库Mysql,并将结果添加到Redis中,并返回
     * 如果存在,直接将结果在Redis查询,并返回
     */
    public User selectById(String id){
//        redisTemplate.hasKey()判断整个key是否存在
        if(redisTemplate.opsForHash().hasKey("user",id)){
            return (User)redisTemplate.opsForHash().get("user",id);

        }else{
            log.info("------->查询Mysql数据库");
            User user = new User();
            user.setId(id);
            user.setName("rzk");
            user.setAge(12);
            /**
             * @param h 用户实体 user
             * @param hk 用户主键 id
             * @param hv 整个对象
             */
            redisTemplate.opsForHash().put("user",id,user);
            return user;
        }
    }

第一次查询

第二次查询

原文地址:https://www.cnblogs.com/rzkwz/p/13331670.html