从.Net到Java学习第八篇——SpringBoot实现session共享和国际化

从.Net到Java学习系列目录

SpringBoot Session共享

修改pom.xml添加依赖

        <!--spring session-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

添加配置类RedisSessionConfig

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60)//默认是1800秒过期,这里测试修改为60秒
public class RedisSessionConfig {
}

添加一个控制器类SessionController来进行测试

复制代码
@RestController
public class SessionController {
    @RequestMapping("/uid")
    String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }
        session.setAttribute("uid", uid);
        return session.getId();
    }
}
复制代码

先访问http://localhost:8083/boot/uid

然后修改配置文件application.yml

spring:
  profiles:
    active: test

重新运行IDEA,test配置文件配置的端口是8085,所以浏览器输入http://localhost:8085/boot/uid

我们看到两个uid是一样的。

在这里我是使用spring boot redis来实现session共享,你还可以配合使用nginx进行负载均衡,同时共享session。

关于nginx可以参考我的另一篇文章:Nginx详解-服务器集群

spring boot 国际化

在spring boot中实现国际化是很简单的的一件事情。

(1)在resources目录下面,我们新建几个资源文件,messages.properties相当于是默认配置的,当其它配置中找不到记录的时候,最后会再到这个配置文件中去查找。

messages.properties
messages_en_US.properties
messages_zh_CN.properties

依次在这三个配置文件中添加如下配置值:

msg=我是中国人
msg=I'm Chinese
msg=我是中国人

添加完之后,会自动将这几个文件包在一块

需要注意的是这个命名是有讲究的,messages.properties部分是固定的,不同语言的话,我们可以在它们中间用_区分。为什么是固定的命名,因为源码是硬编码这样命名的。

(2)新建一个配置文件LocaleConfig

复制代码
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleConfig extends WebMvcConfigurerAdapter {

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认语言
        slr.setDefaultLocale(Locale.CHINA);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}
复制代码

(3)在控制器中,我们添加测试用的方法

复制代码
    //    i18n
    @RequestMapping("/")
    public String i18n() {
        return "i18n";
    }

    @RequestMapping("/changeSessionLanauage")
    public String changeSessionLanauage(HttpServletRequest request, HttpServletResponse response, String lang){
        System.out.println(lang);
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if("zh".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("zh", "CN"));
        }else if("en".equals(lang)){
            localeResolver.setLocale(request, response, new Locale("en", "US"));
        }
        return "redirect:/";
    }
复制代码

(4)添加视图来展示,在templates下新建文件i18n.html,通过#可以直接获取国际化配置文件中的配置项的值。

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>$Title$</title>
</head>
<body>
<a href="/changeSessionLanauage?lang=en">English(US)</a>
<a href="/changeSessionLanauage?lang=zh">简体中文</a>
<br />

<h3 th:text="#{msg}"></h3>
<h4 th:text="${message}"></h4>
</body>
</html>
复制代码

(5)运行查看效果

posted @   邹琼俊  阅读(2400)  评论(10编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
-->
点击右上角即可分享
微信分享提示