SpringBoot中使用Redis

SpringBoot中使用Redis
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码

SpringBoot中使用Redis

redis的应用场景:

  • 缓存(数据查询、短连接、新闻内容、商品内容等等)。(最多使用)
  • 分布式集群架构中的session分离。
  • 聊天室的在线好友列表。
  • 任务队列。(秒杀、抢购、12306等等)
  • 应用排行榜。
  • 网站访问统计。
  • 数据过期处理(可以精确到毫秒)

利用SpringBoot可以快速在项目中加入redis关系数据库。

redis.properties

#多redis连接配置
spring.redis.shard.hostname =192.168.10.110
spring.redis.shard.password =
spring.redis.shard.port = 6379

spring.redis.pool.maxIdle = 20
spring.redis.pool.maxTotal = 500
spring.redis.pool.numTestsPerEvictionRun = 3
spring.redis.pool.testOnBorrow = true
spring.redis.pool.blockWhenExhausted = false
spring.redis.pool.testOnReturn = false

redis配置类

@Component
@PropertySource("redis.properties")
public class JedisConfig implements Serializable {
   

    private static final long serialVersionUID = 1L;

    @Value("${spring.redis.shard.hostname}")
    private String hostname;
    @Value("#{${spring.redis.shard.port}}")
    private int port;
    @Value("${spring.redis.shard.password}")
    private String password;
    @Value("#{${spring.redis.pool.maxIdle}}")
    private Integer maxTotal;
    @Value("#{${spring.redis.pool.maxTotal}}")
    private Integer maxIdle;

    private boolean testOnBorrow;
    private boolean testOnReturn;

    public String getHostname() {
   
        return hostname;
    }

    public void setHostname(String hostname) {
   
        this.hostname = hostname;
    }

    public int getPort() {
   
        return port;
    }

    public void setPort(int port) {
   
        this.port = port;
    }

    public String getPassword() {
   
        return password;
    }

    public void setPassword(String password) {
   
        this.password = password;
    }

    public Integer getMaxTotal() {
   
        return maxTotal;
    }

    public void setMaxTotal(Integer maxTotal) {
   
        this.maxTotal = maxTotal;
    }

    public Integer getMaxIdle() {
   
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
   
        this.maxIdle = maxIdle;
    }




    public boolean isTestOnBorrow() {
   
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
   
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
   
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
   
        this.testOnReturn = testOnReturn;
    }

    @Override
    public String toString() {
   
        return "JedisConfig{" +
                "hostname='" + hostname + '\'' +
                ", port=" + port +
                ", password='" + password + '\'' +
                ", maxTotal=" + maxTotal +
                ", maxIdle=" + maxIdle +
                ", testOnBorrow=" + testOnBorrow +
                ", testOnReturn=" + testOnReturn +
                '}';
    }

使用redisTemplate 经行redis操作

@Configuration
public class JedisConfiguration {
   
    @Autowired
    JedisConfig redisConfig;
    public JedisConnectionFactory convertJedisConnectionFactory() {
   

        System.out.println(redisConfig);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(redisConfig.getHostname());
        jedisConnectionFactory.setPort(redisConfig.getPort());
        jedisConnectionFactory.setPassword(redisConfig.getPassword());

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisConfig.getMaxTotal());
        jedisPoolConfig.setMaxIdle(redisConfig.getMaxIdle());
        jedisPoolConfig.setMinIdle(20);
       jedisPoolConfig.setMaxWaitMillis(300000000);
        jedisPoolConfig.setTestOnBorrow(redisConfig.isTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(redisConfig.isTestOnReturn());
       // jedisPoolConfig.setTestWhileIdle();

        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    @Bean(name = "redisTemplate")
    public StringRedisTemplate convertStringRedisTemplate() {
   
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(convertJedisConnectionFactory());
        stringRedisTemplate.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());   //在这里可以设置序列化方式 这种方式可以将保存在redis 以json的形式
        return stringRedisTemplate;
    }



    @Bean(value = "template")
    public RedisTemplate<String,Object>redisTemplate()
    {
   
        RedisTemplate<String,Object> template =new RedisTemplate<>();
        template.setConnectionFactory(convertJedisConnectionFactory());

        Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om=new ObjectMapper();
        //指定序列化的域
        om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        //指定序列化输入的类型(排除final类型)
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jsonRedisSerializer.setObjectMapper(om);

        //主体选择序列化方式 JSON
        template.setDefaultSerializer(jsonRedisSerializer);


        //Map部分
        //序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        //设置hash key和value的序列化模式
        template.setHashKeySerializer( new StringRedisSerializer());
        template.setHashValueSerializer(jsonRedisSerializer);

        //表示设定结束
        template.afterPropertiesSet();
        return template;
    }


    //一对一的数据类型
    @Bean(name ="ObjectredisTemplate")
    public ValueOperations<String,Object>valueOperations(RedisTemplate<String,Object> template)
    {
   
        return  template.opsForValue();
    }

}

测试类

@Controller
public class maincontroller {
   

    @Resource(name = "ObjectredisTemplate")
    ValueOperations<String,Object> valueOperations;


    @Resource(name = "redisTemplate")
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    JedisConfig redisConfig;
    @RequestMapping("/")
    public void test() throws Exception
    {
   

        /* System.out.println("已被访问"); System.out.println(redisConfig); String a= stringRedisTemplate.opsForValue().get("a"); */

// JSONObject jsonObject =new JSONObject();
// jsonObject.put("name","罗成");
// jsonObject.put("年龄",18);
//
// valueOperations.set("user",jsonObject);



        //JSONObject jsonObject1=(JSONObject) valueOperations.get("user");


        System.out.println();


        Thread thread =new Thread(new Runnable() {
   
            @Override
            public void run() {
   

                String a=stringRedisTemplate.opsForValue().get("a");
                System.out.println(a);

                User user =new User();
                user.setName("hahah");
                user.setAge(5);
                valueOperations.set(user.getName(),user);


                User user1 =(User) valueOperations.get(user.getName());
                System.out.println(user1);

            }
        });
        thread.start();
        thread.join();




    }

执行结果

这里写图片描述

在这里插入图片描述

本文来源蹊源的奇思妙想,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/14757

发表评论